有什么区别:
[xyz]
[x|y|z]
如果有的话?[] 和 | 指定替代方案。
以下代码打印完全相同的结果:
String string = "the x and the y and the z and the nothing";
evaluatePattern(Pattern.compile("\\w*[xyz]\\w*"), string);
evaluatePattern(Pattern.compile("\\w*[x|y|z]\\w*"), string);
有什么区别:
[xyz]
[x|y|z]
如果有的话?[] 和 | 指定替代方案。
以下代码打印完全相同的结果:
String string = "the x and the y and the z and the nothing";
evaluatePattern(Pattern.compile("\\w*[xyz]\\w*"), string);
evaluatePattern(Pattern.compile("\\w*[x|y|z]\\w*"), string);
[xyz]只匹配三个字符 - x, y, z. 这和(x|y|z)
[x|y|z]匹配 4 个字符 - x, y, z, |. 这和(x|y|z|\|)
请注意,在Character Classpipe(|)中没有特殊意义。
正如其他人所说,将[x|y|z]匹配四个字符之一 - x、y或。这是因为,在字符类内部(与正则表达式中的其他地方不同),大多数时候唯一的“特殊字符”是,它结束了字符类。z|]
同样, this:将[.^$|]匹配五个字符之一 - .、^或。$|
此规则有一些“例外” - 例如:[^abc]将匹配任何不是 a或b的单个字符c。您还可以指定一个字符范围——例如,[a-z]匹配任何一个小写字母。
还应该注意的是,对于大多数正则表达式引擎,虽然字符 like.不需要在字符类中转义,但 a\仍然被认为是试图转义它们。例如,[\.]仅匹配字符.,而[\\.]匹配字符之一\或.。
可以在此处找到对字符类的更详尽解释:http ://www.regular-expressions.info/charclass.html 。特别要注意标题为“字符类中的元字符”的部分。
该模式[x|y|z]将匹配 string "|",而[xyz]不会。方括号创建一个字符类,其中包括字符x、、、和。yz|
如有疑问,只需检查此备忘单以获取不同正则表达式和规则的示例。
希望能帮助到你。
[xyz] is a set of the characters x, y and z[x|y|z] is the set of the characters x, y and z along with |One of them has an extra character that it will match.
[xyz] is effectively equivalent to (?:x|y|z), though they may have different internal representations. The second is probably slower. I just changed it to remove the capturing group.