KDJ KDJ - 3 years ago 220
Java Question

Java Regexp matching exact word

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download