简体   繁体   English

检查 Java \\$ 或 \\ 中的一组特定元字符,

[英]Check a specific set of metacharacters in Java \$ or \,

I need to check a specific set of the special characters: \\$ or \\, is present in String.我需要检查一组特定的特殊字符: \\$\\,是否存在于字符串中。 Example;例子;

  1) \\ghg$ : invalid
  2) \\ghg\\$ : valid
  3) ghg$ : invalid
  4) \\ghg\\,$ : invalid. Here $ is not escaped 
  5) ghg\\,\\$ : valid

Below is the code,下面是代码,

private static void regexValidation(String text, String pattern) {
        System.out.println(text + " and pattern " + pattern + " used" + ":" + text.matches(pattern) + " with pattern "
                + Pattern.compile(pattern).matcher(text).matches() + " with find "
                + Pattern.compile(pattern).matcher(text).find());
    }

The pattern used was pattern = ".*\\\\$.*";使用的模式是pattern = ".*\\\\$.*"; which didnt give the expected result.这没有给出预期的结果。 Was using ".*\\\\B\\\\$\\\\B.*" but this also fails in the 4th case.正在使用".*\\\\B\\\\$\\\\B.*"但这在第 4 种情况下也失败了。 Is there a way in java we can do filter the special character set? java中有没有办法过滤特殊字符集?

seems your requirement is not very clear:看来你的要求不是很清楚:

according to your \\$ or \\, , then \\\\ghg\\\\,$ should match, for it contain the \\\\, , which match \\,根据您的\\$ or \\, ,然后\\\\ghg\\\\,$应该匹配,因为它包含\\\\, ,它匹配\\,

so if your requirement is: match \\$ or \\, , then所以如果你的要求是:匹配\\$\\, ,那么

if you just want to test match or not, can use:如果您只想测试匹配与否,可以使用:

  • regex: (((?<=\\\\)\\$)|(\\\\,))正则表达式: (((?<=\\\\)\\$)|(\\\\,))
  • result:结果:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM