Home > Mobile >  Regex isn't being matched
Regex isn't being matched

Time:03-16

This is the code:

String newtask = "newTask[\\{] taskId\"(?<id>\\d{1,4})\", username\"\\w([_\\w\\d&&^(bahmanBAHMAN)]){6,15}\\d\", isValid\"(?<isitthough>(no|yes))\", name\"[\\w\\s]*\", address\"(?<address>[\\w\\s] [-]\\d{8,10})\", date\"(?<date>\\d{8})\", info\"(?<info>[^\"]*)\", price\"(?<price>\\d \\.{0,1}\\d*)\" "; String changeaddress = "changePlace[\\{] taskId\"(?<idtobechanged>\\d{1,4})\", newAddress\"(?<theaddress>[\\w\\s] [-]\\d{8,10})\" ";
Pattern addingpat = Pattern.compile(newtask);
String command=scanner.nextLine();
Matcher addingmat = addingpat.matcher(command);
if (addingmat.find())
System.out.println("it has matched");

And what the user will type in terminal:

newTask{ taskId"1", username"AyesItsGoood4", isValid"yes", name"reza", address"LeninGrad-12345678", date"19410908", info"do the task", price"1.57" 

It isn't printing anything. I would be really thankful if somone pointed out the problem of this code. Thanks for reading.

CodePudding user response:

The regex needs to be fixed where you tried to use character class subtraction:

newTask[\{] taskId\"(?<id>\d{1,4})\", username\"[a-zA-Z][a-zA-Z&&[^bahmnBAHMN]]{6,15}\d\", isValid\"(?<isitthough>no|yes)\", name\"[\w\s]*\", address\"(?<address>[\w\s] -\d{8,10})\", date\"(?<date>\d{8})\", info\"(?<info>[^\"]*)\", price\"(?<price>\d \.?\d*)\"

See the regex demo.

The \w([_\w\d&&^(bahmanBAHMAN)]){6,15}\d\" is replaced with (?!(?i:bahman\"))\w{7,16}\d\". Here is why:

  • \w([_\w\d&&^(bahmanBAHMAN)]){6,15}\d - matches a word char (with \w), then 6-15 occurrences a b, a, h, m, n, B, A, H, M, N char, and then a digit. This happens because what you used is a character class intersection, and the [_\w\d&&^(bahmanBAHMAN)] pattern matches only those chars that are present both in the [_\w\d] and [^(bahmanBAHMAN)] charsets.
  • The [a-zA-Z][a-zA-Z&&[^bahmnBAHMN]]{6,15}\d pattern matches a single ASCII letter, then 6 to 15 ASCII letters other than b, a, h, m and n (case insensitive) and then a digit.

In Java:

String newtask = "newTask\\{ taskId\"(?<id>\\d{1,4})\", username\"[a-zA-Z][a-zA-Z&&[^bahmnBAHMN]]{6,15}\\d\", isValid\"(?<isitthough>no|yes)\", name\"[\\w\\s]*\", address\"(?<address>[\\w\\s] -\\d{8,10})\", date\"(?<date>\\d{8})\", info\"(?<info>[^\"]*)\", price\"(?<price>\\d \\.?\\d*)\"";
  • Related