Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Java to match a word that is not part of other word

Tags:

java

regex

I have created this regex for this:

    (?<!\w)name(?!\w)

Which I expect that will match things like:

    name
    (name)

But should not match things like:

    myname
    names

My problem is that if I use this pattern in Java it doesn't work for the case where other symbols different than whitespaces are used, like brackets.

I tested the regex in this site (http://gskinner.com/RegExr/, which is a very nice site btw) and it works, so I'm wondering if Java requires a different syntax.

    String regex = "((?<!\\w)name(?!\\w))";
    "(name".matches(regex); //it returns false
like image 568
xsilmarx Avatar asked Jan 18 '26 10:01

xsilmarx


1 Answers

Why not use word boundary?

Pattern pattern = Pattern.compile("\\bname\\b");
String test = "name (name) mynames";
Matcher matcher = pattern.matcher(test);
while (matcher.find()) {
    System.out.println(matcher.group() + " found between indexes: " + matcher.start() + " and " + matcher.end());
}

Output:

name found between indexes: 0 and 4
name found between indexes: 6 and 10
like image 145
Mena Avatar answered Jan 21 '26 01:01

Mena



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!