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
There is no \b word boundary in the middle of "% "; that's why your pattern fails.
Use this pattern instead:
"\\b90%"
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 "% ".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With