I've been using http://www.regexplanet.com/advanced/java/index.html to test a regular expression I've written.
The regular expression is : \A[\d+(-\d+){0,1}\|\d+\|\d+\|[YN]{1}](,[\d+(-\d+){0,1}\|\d+\|\d+\|[YN]{1}])*\z
I'm trying to match strings of the form '[30-41|2|21|Y]' OR '[15-23|45|12|Y],[15|42|6|Y]' etc
The regular expression seems to work perfectly when testing on that site however when I use it in my own java code (see below) it gives me unexpected matches (I have pasted the console output below the code). Does anyone know what I'm doing wrong here?
EDIT : As pointed out by stema, I had the input string and pattern in the wrong order when creating the Pattern and Matcher. I have swapped these round now but am now getting 'no match found'.
public static void testRegex(String inputString){
String regex = "\\A\\[\\d+(\\-\\d+){0,1}\\|\\d+\\|\\d+\\|[YN]{1}\\](,\\[\\d+(\\-\\d+){0,1}\\|\\d+\\|\\d+\\|[YN]{1}\\])*\\z";
Pattern pattern = Pattern.compile(inputString);
Matcher matcher = pattern.matcher(regex);
boolean found = false;
while(matcher.find()){
System.out.println("Found at :");
System.out.println("start - " + matcher.start());
System.out.println(", end - " + matcher.end() + ". ");
found = true;
}
if(!found){
System.out.println("no match found");
}
}
public static void main(String[] args){
testRegex("[61|12|6]");
}
The console output I'm getting :
Found at : start - 17 , end - 18. Found at : start - 20 , end - 21. Found at : start - 25 , end - 26. Found at : start - 30 , end - 31. Found at : start - 36 , end - 37. Found at : start - 57 , end - 58. Found at : start - 60 , end - 61. Found at : start - 65 , end - 66. Found at : start - 70 , end - 71. Found at : start - 76 , end - 77.
Your code is wrong
Pattern pattern = Pattern.compile(inputString);
Matcher matcher = pattern.matcher(regex);
you need to compile the pattern and not the input string, this should work better:
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
With your "pattern" [61|12|6] you are finding the "1" and the "|" in the regex.
Update
You don't cover the input strings pattern ([61|12|6]) in your regex, because the fourth part where you test for \\|[YN] is not optional. Try this:
\\A\\[\\d+(\\-\\d+)?\\|\\d+\\|\\d+(?:\\|[YN])?\\](,\\[\\d+(\\-\\d+)?\\|\\d+\\|\\d+(?:\\|[YN])?\\])*\\z
See it here on Regexr
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