F Scott Fitzgerald

Total Post:29

Posted by  F Scott Fitzgerald
 1428  View(s)
Rate this:

Please help me with the pattern matching. I want to build a pattern which will match the word starting withj- or c- in the following in a string (Say for example)

[j-test] is a [c-test]'s name with [foo] and [bar]

The pattern needs to find [j-test] and [c-test] (brackets inclusive).

What I have tried so far?

String template = "[j-test] is a [c-test]'s name with [foo] and [bar]";
Pattern patt = Pattern.compile("\\[[*[j|c]\\-\\w\\-\\+\\d]+\\]");
Matcher m = patt.matcher(template);
while (m.find()) {

And its giving output like


which is wrong. Please help me, thanks for your time on this thread.

  1. Babe Zaharias


    Re: Java pattern for [j-*]

    Inside a character class, you don't need to use alternation to match j or c. Character class itself means, match any single character from the ones inside it. So, [jc] itself will match either j or c.

    Also, you don't need to match the pattern that is after j- or c-, as you are not bothered about them, as far as they start with j- or c-.

    Simply use this pattern:

    Pattern patt = Pattern.compile("\\[[jc]-[^\\]]*\\]");

    To explain:

    Pattern patt = Pattern.compile("(?x)      "   // Embedded flag for Pattern.COMMENT
                                 + "\\[       "   // Match starting `[`
                                 + "    [jc]  "     // Match j or c
                                 + "    -     "     // then a hyphen
                                 + "    [^    "     // A negated character class
                                 + "       \\]"        // Match any character except ] 
                                 + "    ]*    "     // 0 or more times
                                 + "\\]       "); // till the closing ]

    Using (?x) flag in the regex, ignores the whitespaces. It is often helpful, to write readable regexes.



Enter your email address here always to be updated. We promise not to spam!