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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With