java - Why does this negative lookbehind fixed length regex not work? -
i'm trying match single '1' in space-separated number list. here's sample code:
public class regextester { public static void main(string[] args) { string test1 = "1 2"; string test2 = "2 1 2"; string test3 = "2 11 2"; string regex = "(?<!\\d)1(?!\\d)"; system.out.println("matches 1: " + test1.matches(regex)); system.out.println("matches 2: " + test2.matches(regex)); system.out.println("matches 3: " + test3.matches(regex)); } }
output is:
matches 1: false matches 2: false matches 3: false
but should (imo):
matches 1: true matches 2: true matches 3: false
lookbehind of fixed length, i'm confused why regex doesn't match. appreciate if know why and/or can provide alternative working regex case.
thank you.
your regex correct. problem matches
method checks if entire input string can matched regex, not if contains substring can matched regex.
maybe use find()
method matcher
class instead.
string test1 = "1 2"; string test2 = "2 1 2"; string test3 = "2 11 2"; string regex = "(?<!\\d)1(?!\\d)"; pattern p = pattern.compile(regex); system.out.println("matches 1: " + p.matcher(test1).find()); system.out.println("matches 2: " + p.matcher(test2).find()); system.out.println("matches 3: " + p.matcher(test3).find());
output:
matches 1: true matches 2: true matches 3: false
update:
if need use matches
can add .*
@ start , end of regex parts beside required 1 consumed regex.
string regex = ".*(?<!\\d)1(?!\\d).*"; system.out.println("matches 1: " + test1.matches(regex)); system.out.println("matches 2: " + test2.matches(regex)); system.out.println("matches 3: " + test3.matches(regex));
output:
matches 1: true matches 2: true matches 3: false
Comments
Post a Comment