xsilmarx
xsilmarx

Reputation: 749

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

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

Upvotes: 3

Views: 1473

Answers (2)

Bohemian
Bohemian

Reputation: 425033

Use the "word boundary" regex \b:

if (str.matches(".*\\bname\\b.*")
    // str contains "name" as a separate word

Note that this will not match "foo _name bar" or "foo name1 bar", because underscore and digits are considered a word character. If you want to match a "non-letter" around "name", use this:

if (str.matches(".*(^|[^a-zA-Z])name([^a-zA-Z]|$).*")
    // str contains "name" as a separate word

See Regex Word Boundaries

Upvotes: 3

Mena
Mena

Reputation: 48404

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

Upvotes: 5

Related Questions