this question has answer here:
- why doesn't regex work expected in java? 3 answers
i'm trying make regex in java returns true if repeated characters present in input string , false otherwise, regex short possible (for code-golf challenge). i'm not @ regexes, thought trick:
(.)\\1
where (.)
character , \\1
reference match found in first part of regex.
however, if try input "1223
", doesn't work:
public static void main(string[] a){ system.out.println(java.util.regex.pattern.matches("(.)\\1", "1223")); }
this return false, while i'm expecting true because of 22
.
does know how fix regex using java.util.regex.pattern.matches
, or shorter, since it's code-golf? ;)
matches
consumes whole string: first .
matches "1", \\1
attempts match "1" next character, , fails.
you have 2 options:
- use
find
, or - change regex
.*(.)\\1.*
explanation:
the second option works because .*
first match whole string, it'll fail match \\1
, backtracks char char until .*
matched "1", (.)\\1
match "22", , final .*
match rest of string.
Comments
Post a Comment