正则表达式不匹配

Regex isn't being matched

这是代码:

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");

以及用户将在终端中输入的内容:

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

它没有打印任何东西。 如果有人指出这段代码的问题,我将非常感激。 感谢阅读。

正则表达式需要在您尝试使用字符 class 减法的地方修复:

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*)\"

参见regex demo

\w([_\w\d&&^(bahmanBAHMAN)]){6,15}\d\" 替换为 (?!(?i:bahman\"))\w{7,16}\d\"。原因如下:

  • \w([_\w\d&&^(bahmanBAHMAN)]){6,15}\d - 匹配单词 char(\w),然后出现 6-15 次 bahmnBAHMN 字符,然后是数字。发生这种情况是因为您使用的是 character class intersection,而 [_\w\d&&^(bahmanBAHMAN)] 模式仅匹配 [_\w\d][^(bahmanBAHMAN)] 字符集中存在的那些字符。
  • [a-zA-Z][a-zA-Z&&[^bahmnBAHMN]]{6,15}\d 模式匹配单个 ASCII 字母,然后是 bahmh 以外的 6 到 15 个 ASCII 字母n(不区分大小写)然后是数字。

在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*)\"";