为文字字符、特殊字符和"+"创建模式



我尝试为文字字符、几个特殊字符和+创建模式,但没有成功。

我使用它作为示例正则表达式模式,包括所有特殊字符 这是我的正则表达式,但根据 http://www.regexplanet.com/advanced/java/index.html 字符串+不匹配:

[a-zA-Zx43-_#@.:;/\=!^() ]+

我错过了什么?

你必须把-放在最后,否则x43-_意味着介于C的 ASCII 和_的 ACSII 之间的任何内容:

[a-zA-Zx43_#@.:;/\=!^() +-]+

Regex101 告诉我们,之前,-的意思是:

x43-_ a single character in the range between C (ASCII 67) and _ (ASCII 95) (case sensitive)

如果你把它移到最后:

=!^() +- matches a single character in the list =!^() +- (case sensitive)

+可以用作字符组中的文本。x43用于C,所以我认为您在这里混淆了 ASCII 代码,只需将其删除并用作文字+即可。

43 是+十进制ASCII 代码。

但是你写了x43-_意思是:一系列字符之间C(十六进制43)和_.

我想,您在这里想要的不是任何范围,而只是 3 个文字字符:

  • 减去
  • 下划线 (_)。

如果是这种情况,请将此片段更改为+-_(加号可以按原样给出,[]之间的"字面"减号需要用引用, 和未得分可以保持原样)。

使用此正则表达式,它应该可以工作:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "[a-zA-Z_#@.:;\/\\=!^() +-]+";
final String string = "+";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}

最新更新