Reputation: 79
I have this java regular expression.
Pattern regex = Pattern.compile("(\\£\\d[\\d\\,\\.]+)[k|K]");
Matcher finder = regex.matcher(price);
if(finder.find()){
etc;
}
Note ... java
I'm trying to match whole word k or K not kilo or kilometer. IVe tried \\bk\\b but the online testers show no match. Has it something to do with square brackets.
Thank you in advance
Upvotes: 0
Views: 85
Reputation: 626926
Beside the fact that currently your pattern matches a k
or K
before any char, it does not match values like £1k
as the +
quantifier requires another digit, dot or comma before k
or K
.
Also note that [\\b]
does not match a word boundary, it only matches a b
letter.
Putting a \b
between [\\d\\,\\.]+
and [k|K]
is not a good idea since there is always a word boundary between .
/ ,
and k
, and there is no word boundary between a digit and k
.
You need to use
Pattern regex = Pattern.compile("(£\\d[\\d,.]*)[kK]\\b");
Details
(£\\d[\\d,.]*)
- Group 1:
£
- a pound sign\\d
- a digit[\\d,.]*
- zero or more digits, ,
or .
[kK]
- a k
or K
\\b
- a word boundary (there must be end of string or a non-word char after k
or K
)Upvotes: 1