Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match word '90%' using regular expression

Tags:

java

regex

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

like image 621
user327126 Avatar asked Sep 10 '26 22:09

user327126


1 Answers

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

Use this pattern instead:

"\\b90%"

See also

  • regular-expressions.info/Word boundaries

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 "% ".

like image 200
polygenelubricants Avatar answered Sep 13 '26 12:09

polygenelubricants



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!