user3387870
user3387870

Reputation: 1

Pattern Matcher not working for whiteSpace

I am trying to search below word using pattern Matcher java

Word to search in doc:

 (peak: somevalue) [

code:

Matcher m= Pattern.compile("\\(peak:(.*?)\\)\\s[").matcher(currLine);

but not getting the expected result.

want to get value of "somevalue" using the pattern, could you please guide me.

Upvotes: 0

Views: 92

Answers (3)

Pshemo
Pshemo

Reputation: 124225

You need to escape [ at the end of your regex because it is also one of its metacharacter used to create [...] character class

Pattern.compile("\\(peak:(.*?)\\)\\s\\[")
//here -----------------------------^^

and you can add \\s? before (.*?) to not include space after peak: in match from group 1.

So your code can look like

Matcher m =  Pattern.compile("\\(peak:\\s?(.*?)\\)\\s\\[").matcher(currLine);
if(m.find())
    System.out.println(m.group(1));
//                            ^^^ group 1 will contain match from `(.*?)`

BTW it looks like instead of regex you should be using parser of language you are trying to analyse. Regex can give you many problems like false-positive matches if you use .*? because dot . can accept any character so in your case pattern "\\(peak:\\s?(.*?)\\)\\s\\[" will accept any string which starts with (peak: and ends with ) [ like (peak:whatever)()<foo>{bar}{}(blah) [.

To solve this kind of problem you will need to be more specific with what kind of characters should be accepted as whatever. One of ideas is to let it accept characters which are not ) so you could try with

Pattern.compile("\\(peak:\\s?([^)]*?)\\)\\s\\[")
//                            ^^^^ means any character except `)`

Upvotes: 1

Jens
Jens

Reputation: 69440

This code gives you the correct result:

    String s="(peak: somevalue) [";
    Matcher m= Pattern.compile("\\(peak:(.*?)\\)\\s\\[").matcher(s);

    m.find();
    System.out.println(m.group(1));

Upvotes: 1

Edwin Buck
Edwin Buck

Reputation: 70909

You need a \s between your colon and the "anything capture" of (.*?)

Upvotes: 0

Related Questions