Regular Expressions - matching a brace

I am a bit of a begginner when it comes to regular expressions - but I am trying to replace all curly braces - {} in a string with normal brackets - ().
This is how I'm trying to do it -
//replace any curly braces with normal brackets
Pattern p = Pattern.compile("{");
Matcher m = p.matcher(value);
value = m.replaceAll("(");
However, I get an exception when my code is run: "java.util.regex.PatternSyntaxException: Illegal repetition {"
Any idea how to replace a brace character? Also, is there an easy way to replace both the open brace - { and close brace - } characters in one expression?
Regards,
Jake

..Also, is there an easy way to replace both the open brace - {
and close brace - } characters in one expression?
  // only for paired curly braces
  while (target.matches(".*\\{(.*)\\}.*")) {
    target = target.replaceAll("\\{(.*)\\}", "($1)");

Similar Messages

  • Get all groups from a regular expression match

    Please help me understand how to use Java regular expressions:
    I have an expression similar to this:
    {noformat}"([^X]+)(X[^X]*)+"{noformat}This should match stuff like "asaasaXdfdfdfXXsdsfd".
    How does one access all the matches for the second group (the second groups has a Kleene operator
    added so it is not really just one group --- but match.groupCount() is always 2)
    Here is roughly the code:
    {noformat}java.util.regex.Pattern pattern = {noformat}{noformat}java.util.regex.Pattern.compile({noformat}{noformat}"([^X]+)(X[^X]*)+",{noformat}{noformat}java.util.regex.Pattern.MULTILINE{noformat}{noformat});{noformat}{noformat}java.util.regex.Matcher matcher = pattern.matcher(text);{noformat}{noformat}matcher.find();{noformat}{noformat}int groupcount = matcher.groupCount();{noformat}
    Also, without matcher.find() I get an illegalStateException .. which I also get if I use matcher.matches() instead
    of matcher.find().
    I am obviously missing something here. There is always at least one "X" in the string so shouldn't that pattern always
    match the whole string? Since there are often multiple X, shouldnt I get a group for each occurrence of X, followed
    by 0 or more other characters?
    {noformat}But when I try to match everything by using "^([^X]+)(X[^X]*)+$" I get an "IllegalStateException: No match available" again.{noformat}
    What is the correct way to do this?
    Edited by: johann_p on May 16, 2008 10:39 AM

    I am sorry I messed this up. Here is a SSCCE:
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    class RegExp1 {
        public static void main(String[] args) {
          String testString = "first|aaaa | bbbb\n|cccc|ddddd";
          Pattern pattern = Pattern.compile("^([^|]+)(\\|[^|]*)+$");
          Matcher matcher = pattern.matcher(testString);
          matcher.find();
          int groupcount = matcher.groupCount();
          System.out.println("Found "+groupcount+" groups");
          System.out.println("Matcher: "+matcher);
          for (int i = 1; i <= groupcount; i++) {
            System.out.println("Match "+i+": "+testString.substring(matcher.start(i),matcher.end(i)));
    }I figured out a small bug in my first code that explains some of the exception oddities, but my principal question remains:
    how do I access all the matches that correspond to the second capturing group?
    In the example I would get "first" for Match 1 and "|ddddd" for Match 2, but how do I access all the matches??
    Thank you for your help!

  • Uri regular expression matching

    Hi, for some reason I cannot get a uri to match the following regular expression check.
    <If $uri !~ '^/dir/\?somename=(.*)'>
    NameTrans fn="restart" uri="/shownomatch?uriwas=$uri"
    </If>
    <Else>
    NameTrans fn="restart" uri="/showamatch?value=$1"
    </Else>I can see in the page that is restarted to that it should match by printing out the uriwas parameter.
    An example uri that should match but doesn't is /dir/?somename=5f801297-a8f6-42a4-933d-660f2120cd0d
    Any thoughts? I've tried a few different valid regular expressions, but cannot get a match.

    Thank you all for the help.
    My main goal was to provide verification that a user has logged in and has the proper authority to access a directory/resource. What I believe I now have is a check to verify that the user has a required cookie and that the value in the cookie matches the parameter in $query.
    Below is what I now have in the server's obj.conf file. Let me know if you think there is something that I am missing.
    <If $uri =~ '^/ValidationApp/*'>
      <Client security="false">
        NameTrans fn="redirect" url-prefix="https://server.domain.edu"
      </Client>
    </If>
    <If $uri !~ '^/ValidationApp/*'>
      <Client security="true">
        NameTrans fn="redirect" url-prefix="http://server.domain.edu"
      </Client>
    </If>
    <If $uri =~ "/SomeDir/*">
      <If not defined $query or not defined $cookie{"$(lookup('cookiemap.conf','/SomeDir'))"} or $query !~ 'uuid=(.*)' or $& ^ $cookie{"$(lookup('cookiemap.conf','/SomeDir'))"}>
        NameTrans fn="restart" uri="/ValidationApp/CookieCheckServlet?loc=$uri&uid=$(uuid())&ReqInfo=$(lookup('cookiemap.conf','/SomeDir'))"
      </If>
    </If>
    <If $uri =~ "/AnotherDir/*">
      <If not defined $query or not defined $cookie{"$(lookup('cookiemap.conf','/AnotherDir'))"} or $query !~ 'uuid=(.*)' or $& ^ $cookie{"$(lookup('cookiemap.conf','/AnotherDir'))"}>
        NameTrans fn="restart" uri="/ValidationApp/CookieCheckServlet?loc=$uri&uid=$(uuid())&ReqInfo=$(lookup('cookiemap.conf','/AnotherDir'))"
      </If>
    </If>The servlet used in the restart checks to see if the required cookie exists (ReqInfo) and if the uuid value (uid) is set in the session. If so it forwards to the uri (loc). If not it forwards to a login form the checks the user ID/password. It adds the uid to the session, creates the cookie, and forwards back to the requested uri.
    The Client security checks are down to make sure the user uses HTTPS when entering their user ID/Password.

  • Help in regular expression matching

    I have three expressions like
    1) [(y2009)(y2011)]
    2) [(y2008M5)(y2011M3)] or [(y2009M5)(y2010M12)]
    3) [(y2009M1d20)(y2011M12d31)]
    i want regular expression pattern for the above three expressions
    I am using :
    REGEXP_LIKE(timedomainexpression, '???[:digit:]{4}*[:digit:]{1,2}???[:digit:]{4}*[:digit:]{1,2}??', 'i');
    but its giving results for all above expressions while i want different expression for each.
    i hav used * after [:digit:]{4}, when i am using ? or . then its giving no results. Please help in this situation ASAP.
    Thanks

    I dont get your question Can you post your desired output? and also give some sample data.
    Please consider the following when you post a question.
    1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
    You can use the following query and do a copy past of the output.
    select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
    that are asked the answer is already there.
    3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
    I have the following table called sales
    with sales
    as
          select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
          union all
          select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
    select *
      from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
    For example in the above sales table, I want to know the total quantity and number of invoice for each product.
    The output should look like this
    Prod_id   sum_qty   count_inv
    1         145       2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
    6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
    Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
    use the {noformat}{noformat} tags.
    The usage of the tag is like this.
    <place your code here>\
    7. If you are posting a *Performance Related Question*. Please read
       {thread:id=501834} and {thread:id=863295}.
       Following those guide will be very helpful.
    8. Please keep in mind that this is a public forum. Here No question is URGENT.
       So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Regular Expression match for BOM char .

    i am trying to match BOM char in file with regex but \\ufeff seem to be not working .
    please suggest solution on this

    This line               String srcStr = new String(b);will only produce the String you expect if the BOM bytes can be converted to characters under your default character encoding. They probably can't.
    I use this class
    public class BOMStripperInputStream extends PushbackInputStream
        public static final int[][] BOMS =
                0x00, 0x00, 0xFE, 0xFF
                0xFF, 0xFE, 0x00, 0x00
                0x2B, 0x2F, 0x76, 0x38
                0x2B, 0x2F, 0x76, 0x39
                0x2B, 0x2F, 0x76, 0x2B
                0x2B, 0x2F, 0x76, 0x2F
                0xDD, 0x73, 0x66, 0x73
                0xEF, 0xBB, 0xBF
                0x0E, 0xFE, 0xFF
                0xFB, 0xEE, 0x28
                0xFE, 0xFF
                0xFF, 0xFE
        static private int testForBOM(int[] bom, int[] bytes)
            for (int index = 0; index < bom.length; index++)
                if (bom[index] != bytes[index])
                    return 0;
            return bom.length;
        public BOMStripperInputStream(InputStream is) throws IOException
            super(is, 4);
            final int[] bytes =
                read(), read(), read(), read()
            int count = 0;
            for (int[] bom : BOMS)
                count = testForBOM(bom, bytes);
                if (count != 0)
                    break;
            for (int index = bytes.length - 1; index >= count; index--)
                if (bytes[index] != -1)
                    unread(bytes[index]);
    }to get rid of a BOM .

  • Why does this regular expression match (sh)?

    I'm trying to have a yes/no prompt which accepts y, n, yes, no, and is case insensitive. I thought this would work:
    until [[ "$yesno" =~ no?|y(es)? ]]
    do
    read "Continue (yes/no)?" reply;
    yesno=`tr '[:upper:]' '[:lower:]' <<< "$reply"`;
    if [[ "$yesno" =~ no? ]]
    then
    exit 0;
    elif [[ "$yesno" =~ y(es)? ]]
    then
    # stuff to do
    else
    "Invalid input!";
    done
    The problem is ? seems to act more like a wildcard. I tested yn, and it matches. In fact as long as the first character is a Y, y, N, or n, it returns true. The only time ? acts the way it should (match preceding character once or none), is when another character follows it:
    # 'non' and 'noun' will match
    if [[ "$1" =~ nou?n ]]
    then
    echo "$1 matches";
    else
    echo "$1 does not match";
    fi
    I would like to know why it's working like this, and how do I fix it?

    Instead of calling an external program, tr, you could let bash do the case conversion with parameter expansion:
    yesno=${reply,,}
    See 3.5.3 Shell Parameter Expansion.  This is more compact but more cryptic. Take your choice.
    Or you could obviate the need for case conversion altogether by having bash do case-insensitive comparisons:
    shopt -s nocasematch
    But then, to prevent the nocasematch setting affecting the rest of the script, you'd have to save the old value of nocasematch and reset it when you've finished, or carry out the comparisons in a subshell (in which case any other variable settings done in the subshell will also be lost when the subshell ends), so I think it would be more hassle than it's worth.
    Last edited by nh (2009-11-16 17:16:04)

  • Regular expression matches string starts with &

    Hello,
    I am trying to write a Reg Exp that removes any string starts with "&" and Ends with ";" . In other words, I am trying to remove anything similar to:
    & nbsp;  & quot; & lt; & gt;  Any help please.
    This does not work:
    select regexp_replace(ename, '^&[a-z]{2,4}[;]$') from emp;Regards,
    Fateh

    Fateh wrote:
    I am trying to write a Reg Exp that removes any string starts with "&" and Ends with ";" . In other words, I am trying to remove anything similar to:
    & nbsp;  & quot; & lt; & gt; 
    Those are entity references (without the whitespace after '&').
    Do you really want to remove them, or do you actually want to convert them back to their corresponding characters but don't know how to do it?
    SQL> set scan off
    SQL> select utl_i18n.unescape_reference('&#38;quot;Test&#38;quot;:&#38;nbsp;3&#38;gt;2') from dual;
    UTL_I18N.UNESCAPE_REFERENCE('&
    "Test": 3>2

  • Match Regular Expression Function

    Hi guys, using this pattern I got this error:
    -4600 Error occurred during regular expression match.
    I have attached the VI.
    can you help me?thank you
    Solved!
    Go to Solution.
    Attachments:
    Untitled 2.vi ‏30 KB

    inuyasha84 wrote:
    hi well i want to save (create) a file and do a check to see if the new file that I want to create already exist or not. so the idea was to see if the path of the new file is equal to the old path
    Why not just use "Check if file or folder exists"? (File I/O -> Adv File Funcs)
    Cameron
    To err is human, but to really foul it up requires a computer.
    The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
    Profanity is the one language all programmers know best.
    An expert is someone who has made all the possible mistakes.
    To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
    LabVIEW Unit 1 - Getting Started
    Learn to Use LabVIEW with MyDAQ

  • Regular Expressions and String variables

    Hi,
    I am attempting to implement a system for searching text files for regular expression matches (similar to something like TextPad, etc.).
    Looking at the regular expression API, it appears that you can only match using string variables. I just wanted to make sure this is true. Some of these files might be large and I feel uneasy about loading them into ginormous Strings. Is this the only way to do it? Can I make a String as big as I want?
    Thanks,
    -Mike

    Newlines are only a problem if you're reading the
    text line-by-line and applying the regexp to each
    line. It wouldn't catch expressions that span
    lines.
    @sabre150: your note re: CharSequence -- so what
    you're suggesting is to implement a CharSequence that
    wraps the file contents, and then use the regexps on
    the whole thing? I like the idea but it seems like
    it would only be easy to implement if the file uses a
    fixed-width character set. Or am I missing
    something...?You are correct for the most basic implementation. It is very easy to create a char sequence for fixed width character sets using RandomAccessFile. Once you go to character sets such as UTF-8 then more effort is required.
    While ever the regex is moving forward thought the CharSequence one char at a time there is no problem because one can wrap a Reader but once it backtracks then one needs random access and one will need to have a buffer. I have used a ring buffer for this which seems to work OK but of course this will not allow the regex to move to any point in the CharSequence.
    'uncle_alice' is the regex king round here so listen to him.
    :-( I should read further ahead next time!
    Message was edited by:
    sabre150
    Message was edited by:
    sabre150

  • Regular expressions its URGENT !!!

    i have a long string of regular expressions seperated by "|" and i need to know which regular expression the particular string matched how can i find that and can i do it using java .util.regex
    thanks in advance

    Consider to use "capturing groups" or a better solution should be to split this long regular expression with alternations in small ones that will cause considerable reduction in backtracking. Also in this way will be easier to find what regular expression matches the target string.
    Regards.

  • Regular expressions to parse arithmetic expression

    Hello,
    I would like to parse arithmetic expressions like the following
    "5.2 + cos($PI/2) * -5"where valid expression entities are numbers, operations, variables and paranthesis. Until now I have figured out some regular expressions to match every type of entities that I need, and combine them into one big regex supplied to a pattern and matcher. I will paste some code now to see what I wrote:
    public class RegexTest {
        /** A regular expression matching numeric expressions (floating point numbers) */
        private static final String REGEX_NUMERIC = "(-?[0-9]+([0-9]*|[\\.]?[0-9]+))";
        /** A regular expression matching a valid variable name */
        private static final String REGEX_VARIABLE = "(\\$[a-zA-Z][a-zA-Z0-9]*)";
        /** A regular expression matching a valid operation string */
        public static final String REGEX_OPERATION = "(([a-zA-Z][a-zA-Z0-9]+)|([\\*\\/\\+\\-\\|\\?\\:\\@\\&\\^<>'`=%#]{1,2}))";
        /** A regular expression matching a valid paranthesis */
        private static final String REGEX_PARANTHESIS = "([\\(\\)])";
        public static void main(String[] args) {
            String s = "5.2 + cos($PI/2) * -5".replaceAll(" ", "");
            Pattern p = Pattern.compile(REGEX_OPERATION + "|" + REGEX_NUMERIC + "|" + REGEX_VARIABLE + "|" + REGEX_PARANTHESIS);
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println(m.group());
    }The output is
    5
    2
    +
    cos
    $PI
    2
    5There are a few problems:
    1. It splits "5.2" into "5" and "2" instead of keeping it together (so there might pe a problem with REGEX_NUMERIC although "5.2".matches(REGEX_NUMERIC) returns true)
    2. It interprets "... * -5" as the operation " *- " and the number "5" instead of " * " and "-5".
    Any solution to solve these 2 problems are greately appreciated. Thank you in advance.
    Radu Cosmin.

    cosminr wrote:
    So, I've written some concludent examples and the output after parsing (separated by " , " ):
    String e1 = "abs(-5) + -3";
    // output now: abs , ( , - , 5 , ) , + , - , 3 ,
    // should be:  abs , ( , -5 , ) , + , - , 3 , (Notice the -5)
    I presume that should also be "-3" instead of ["-", "3"].
    String e2 = "sqrt(abs($x=1 + -10))";
    // output now: sqrt , ( , abs , ( , $x , = , 1 , + , - , 10 , ) , ) ,
    // should be:  sqrt , ( , abs , ( , $x , = , 1 , + , -10 , ) , ) ,   (Notice the -10)
    String e3 = "$e * -1 + (2 - sqrt(4))";
    // output now: $e , * , - , 1 , + , ( , 2 , - , sqrt , ( , 4 , ) , ) ,
    // should be:  $e , * , -1 , + , ( , 2 , - , sqrt , ( , 4 , ) , ) ,
    String e4 = "sin($PI/4) - 3";
    // output now: sin , ( , $PI , / , 4 , ) , - , 3 , (This one is correct)
    String e5 = "sin($PI/4) - -3 - (-4)";
    // output now: sin , ( , $PI , / , 4 , ) , - , - , 3 , - , ( , - , 4 , ) ,
    // should be:  sin , ( , $PI , / , 4 , ) , - , -3 , - , ( , -4 , ) ,  (Notice -3 and -4)I hope they are relevant, If not I will supply some more.I made a small change to REGEX_NUMERIC and also put REGEX_NUMERIC at the start of the "complete pattern" when the Matcher is created:
    import java.util.regex.*;
    class Test {
        private static final String REGEX_NUMERIC = "(((?<=[-+*/(])|(?<=^))-)?\\d+(\\.\\d+)?";
        private static final String REGEX_VARIABLE = "\\$[a-zA-Z][a-zA-Z0-9]*";
        public static final String REGEX_OPERATION = "[a-zA-Z][a-zA-Z0-9]+|[-*/+|?:@&^<>'`=%#]";
        private static final String REGEX_PARANTHESIS = "[()]";
        public static void main(String[] args) {
            String[] tests = {
                "abs(-5) + -3",
                "sqrt(abs($x=1 + -10))",
                "$e * -1 + (2 - sqrt(4))",
                "sin($PI/4) - 3",
                "sin($PI/4) - -3 - (-4)",
                "-2-4" // minus sign at the start of the expression
            Pattern p = Pattern.compile(REGEX_NUMERIC + "|" + REGEX_OPERATION + "|" + REGEX_VARIABLE + "|" + REGEX_PARANTHESIS);
            for(String s: tests) {
                s = s.replaceAll("\\s", "");
                Matcher m = p.matcher(s);
                System.out.printf("%-21s-->", s);
                while (m.find()) {
                    System.out.printf("%6s", m.group());
                System.out.println();
    }Note that since Java's regex engine does not support "variable length look behinds", you will need to remove the white spaces from your expression, otherwise REGEX_NUMERIC will go wrong if a String looks like this:
    "1 - - 1"Good luck!

  • Cisco IDS/IPS regular expressions

    Is there any way to perform a NOT on a regular expression match. For instance, in PCRE it would be !"/[A-Z]+/i". I cannot determine if there is a valid way to do this on a Cisco IDS regex string. Any help or info would be greatly appreciated.

    To some extent, there is a way to do this. It would need to be anchored, and couldn't contain a repetition operator.
    And by anchored I mean tied to something, otherwise the first not class in the regex below ([^Qq]) would fire on every/any character that was not a Q or q.
    So I can say "not QUIT", regardless of case as follows:
    [^Qq]|[Qq][^Uu]|[Qq][Uu][^Ii]|[Qq][Uu][Ii][^Tt]
    so:
    BLAH([^Qq]|[Qq][^Uu]|[Qq][Uu][^Ii]|[Qq][Uu][Ii][^Tt])
    matches:
    BLAHz
    BLAHqz
    BLAHquiz
    BLAHq1
    etc. etc.
    but would not match:
    BLAHquit
    BLAHQUIT
    BLAHQUit
    etc. etc.
    So yes, but limited.

  • Regular Expressions X Performance

    I'd like know what do they you about the use of Regular Expressions? It's more fast?

    Regular expressions can be interpreted by a DFA and the computational cost of its execution is the same cost of traversing the string char by char.
    To find substrings there are algorithms that can skip a lot of chars during the traversing of the string and they result much faster than the analogus ones based on regular expression. But theese algorithms can't interpret regular expressions they work only on exact strings.
    So when you're looking for an exact string the use of exact string matching is much faster than the use of regular expression matching.
    http://en.wikipedia.org/wiki/String_searching_algorithm
    http://en.wikipedia.org/wiki/Pattern_matching
    http://en.wikipedia.org/wiki/Regular_expression
    Bye Alessandro

  • Regular expression - splitting a string

    I have a long string that I'm trying to split into a series of substrings. I would like each of the substrings to start with "TTL.. I'm fairly certain that I'm missing something very basic here. I've attached my code which yield NO GROUPS. I didn't see another method for returning the text that the regular expression matched.
    String finalLongstring="TTL1,clip1+TTL2+clip3,TTL4,clip4,TTL5,clip5+TTL6+"+
       "clip6+TTL7+clip7,TTL8,clip8,TTL9,clip9,TTL10,clip10,TTL11,clip11,TTL12,clip12,"+
       "TTL13,clip13+TTL14+clip14,TTL15,clip15,TTL16,clip16,TTL17,clip17,"+
       "TTL18,clip18,TTL19,clip19,TTL20,clip20,TTL21,clip21,TTL22,clip22,"+
       "TTL23,clip23,TTL24,clip24,TTL25,clip25,TTL26,clip26,TTL27,clip27,"+
       "TTL28,clip28,TTL29,clip29"
    List<String> chapters = new ArrayList<String>();
              chapters.clear();
              Pattern chapter=null;
              chapter=Pattern.compile("(TTL\\d+([+,]|clip\\d+)*)");
              //                      ||    |  |  | |  |    | |
              //                      ||    |  |  | |  |    | Repeat (commas pluses and clips group) 0 or more times
              //                      ||    |  |  | |  |    one or more digits following 'clip'
              //                      ||    |  |  | |  clip
              //                      ||    |  |  | or..
              //                      ||    |  |  plus or comma symbols
              //                      ||    |  group the +, and clip information together
              //                      ||    one or more digits
              //                      |Match clips starting with TTL
              //                      |
              Matcher cp = chapter.matcher(finalLongstring);  //NO MATCHES!!
              String [] temp = chapter.split(finalLongstring);  //temp =EMPTY STRING ARRAY
              do{
                   String chapterPlus=cp.group(1);
                   if(cp.hitEnd()){break;}
                   chapters.add(chapterPlus);
              }while(true);Thanks in advance for the help.
    Icesurfer

    The main reason your matcher didn't work is because you never told it to do anything. You have to call one of the methods matches(), find() or lookingAt(), and make sure it returns true, before you can use the group() methods. When I did that, your regex worked, but then I modified it to demonstrate a better use of capturing groups, as shown here: import java.util.regex.*;
    public class Test
      public static void main(String... args)
        String str="TTL1,clip1+TTL2+clip3,TTL4,clip4,TTL5,clip5+TTL6+clip6+"+
           "TTL7+clip7,TTL8,clip8,TTL9,clip9,TTL10,clip10,TTL11,clip11,TTL12,clip12,"+
           "TTL13,clip13+TTL14+clip14,TTL15,clip15,TTL16,clip16,TTL17,clip17,"+
           "TTL18,clip18,TTL19,clip19,TTL20,clip20,TTL21,clip21,TTL22,clip22,"+
           "TTL23,clip23,TTL24,clip24,TTL25,clip25,TTL26,clip26,TTL27,clip27,"+
           "TTL28,clip28,TTL29,clip29";
        Pattern p = Pattern.compile("(TTL\\d+)[+,](clip\\d+)[+,]");
        Matcher m = p.matcher(str);
        while (m.find())
          System.out.printf("%6s %s%n", m.group(1), m.group(2));
    }The reason your split() attempt didn't work is because the regex matched all of the text; the split() regex is supposed to match the parts you don't want. In fact, it did split the text, creating a list of empty strings, but then it threw them all away, because split() discards trailing empty fields by default.
    Finally, the hitEnd() method is not appropriate in this context. It and the requireEnd() method were added to support the Scanner class in JDK 1.5. If you want to see how they work, look at the source code for Scanner, but for now, just classify them as an advanced topic. When you're iterating through text with the find() method, you stop when find() returns false, plain and simple.

  • Regular expression breaks with \00 in input string

    I wrote the following code to illustrate the problem.
    Clearly the match should occur in both cases, but it does not occur if \00 is in the input string (within the < > ).
    I am not even searching for \00 or \01. This makes the regular expression match rather useless if you have text that contains data in hex form. I am using Labview 8.2. Is this a known bug? Is there a work around?
    Tammo
    Message Edited by Tammo on 03-06-2008 12:26 PM
    Message Edited by Tammo on 03-06-2008 12:26 PM
    Attachments:
    RegEx1.vi ‏56 KB
    BlockDiagram1.jpg ‏18 KB
    FrontPanel1.jpg ‏18 KB

    There was a brief discussion on this not too long ago.

Maybe you are looking for