user12331
user12331

Reputation: 518

How to find exact match for a word in a string

I have a string like this

This is just a test-like thing. I want to test this

I want to use a regex that will match test, such that it only matches test alone but not something like test-like. What would be the regex for this. I tried "\btest\b" but it doesn't work.

Upvotes: 0

Views: 1330

Answers (3)

Crazy Coder
Crazy Coder

Reputation: 508

Try below regex:

\stest(\.|\s)

Upvotes: 0

Mena
Mena

Reputation: 48404

The word boundary \\b won't work in this case, as the hyphen - is considered to be a "non-word" character too.

Use this instead, with whitespace:

String test = "This is just a test-like thing. I want to test this";
Pattern p = Pattern.compile("(?<=\\s|^)test(?=\\s|$)");
Matcher m = p.matcher(test);
while (m.find()) {
    System.out.println(String.format("Found %s at index %d%n", m.group(), m.start()));
}

Output (pun not intended)

Found test at index 42

Upvotes: 2

vks
vks

Reputation: 67968

(?<=\\s|^)test(?=\\s|$)

Try this.See demo.

http://regex101.com/r/rA7aS3/14

\btest\b wont work cause - is a word boundary.

Upvotes: 3

Related Questions