tags:

views:

103

answers:

3

Hi All,

I want word '90%' to be matched with my String "I have 90% shares of this company".

how can I write regular expression for same?

I tried something like this:

Pattern p = Pattern.compile("\\b90\\%\\b", Pattern.CASE_INSENSITIVE
    | Pattern.MULTILINE);
  Matcher m = p.matcher("I have 90% shares of this company");
  while (m.find()){
   System.out.println(m.group());
 }

but no luck.

Can any one thow some lights on this?

Many thanks, Archi

+1  A: 

The parens "capture" the match:

/^.*(90%).*$/g
Delan Azabani
/(90%)/ is a more succint way of doing this in this case.
Eric
This matches `999990%` (but indeed captures only `90%`), which doesn't seem to be what OP intended.
polygenelubricants
+3  A: 

There is no \b word boundary in the middle of "% "; that's why your pattern fails.

Use this pattern instead:

"\\b90%"

See also

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

So between two characters, a \b exists only between a \W and a \w (in either order).

Both '%' and ' ' are \W, so that's why there's no \b between them in "% ".

polygenelubricants
A: 

What do you want to not match?

Florian Diesch
-1 This is a question not an answer, if you think the question is not clear then you should add a comment to it.
M. Jessup