match word '90%' using regular expression
I want word '90%' to be matched with my String "I have 90% shares of this company".
how can I write regular expressi开发者_开发百科on 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%"
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 "% "
.
The parens "capture" the match:
/^.*(90%).*$/g
精彩评论