如何在使用JavaRegex包验证短语的特殊字符之前,将其列为白名单



嘿,我需要绕过字符串str中子字符串白名单的验证,但字符串的其余部分需要验证特殊字符'<','>','$','#','@'。

假设子字符串在主字符串中的其他位置不重复。

这是主字符串String str = "blah blah blah X has paid $8,894 to the shop owner blah blah blah"

这是子字符串"String whiteList = "x has paid $8,894 to the shop owner"

主字符串的当前验证boolean specialChar = Pattern.compile("<|>|\$|#|@", Pattern.CASE_INSENSITIVE).matcher(str).find();

子字符串whiteList包含不应验证的$,并且应返回false。

如果可能的话,我正在寻找一个使用正则表达式的解决方案。如有任何帮助,我们将不胜感激。谢谢~

绕过它:

String stringToCheck;
int pos = str.indexOf(whiteList);
if (pos >= 0) {
stringToCheck =
str.substring(0, pos) + str.substring(pos + whiteList.length());
} else {
stringToCheck = str;
}
boolean specialChar =
Pattern.compile("[<>$#@]").matcher(stringToCheck).find();

我不了解java。只是好奇,因为正则表达式的参与。

使用这个regex:怎么样

[^s<>$#@]+shas paid [d,]+ to the shop owner
  • 它将只捕获主字符串中所需的部分
  • 此匹配中的变量部分是has之前的单词,我们可以使用^来避免出现此类字符
  • blah blah blah ><$ has paid 8,894 to the shop owner blah blah blah这样的输入将与子字符串不匹配

p.S.很抱歉,如果这与此无关。

最新更新