Regexp检查字符串中的连续3位数

Nee*_*raj 4 java regex

如果字符串包含连续的3位数,我想在java中检查正则表达式.但问题是我的字符串可能包含unicode字符.如果字符串包含unicode字符,它应该跳过unicode字符(跳过4'.在&AND#之后)并且应该进行检查.一些例子是

Neeraj : false
Neeraj123 : true
&#1234Neeraj : false
&#1234Neeraj123 : true
123N&#123D : true
Neeraj&#1234 : false
Neeraj&#12DB123 : true
&#1234 : false
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 7

你需要使用负面的lookbehind断言:

Pattern regex = Pattern.compile(
    "(?<!             # Make sure there is no...           \n" +
    " &\\#            # &#, followed by                    \n" +
    " [0-9A-F]{0,3}   # zero to three hex digits           \n" +
    ")                # right before the current position. \n" +
    "\\d{3}           # Only then match three digits.", 
    Pattern.COMMENTS);
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用它:

Matcher regexMatcher = regex.matcher(subjectString);
return regexMatcher.find();  // returns True if regex matches, else False
Run Code Online (Sandbox Code Playgroud)

  • @BheshGurung:嗯,是的.`matches()`是错误的工具.它希望正则表达式匹配整个字符串.Neeraj询问如何*在字符串中搜索三个不属于Unicode转义序列的数字.这就是`find()`方法的用途.使用正确的工具来完成工作...... (2认同)
  • @BheshGurung:我必须承认我自己对这个问题感到困惑.标题说*找*,内容说*check*...所以我猜你的观点是有效的.但最终,使用这种令人困惑的方法名称是Java的错.:) (2认同)