简体   繁体   English

字符类中的字符顺序在正则表达式中重要吗

[英]Does order of characters in character class matter in regular expressions

I was using character class in regular expression to split a string. 我在正则表达式中使用字符类来拆分字符串。 I had an assumption that order of characters in the character class does not matter. 我假设字符类中字符的顺序无关紧要。

Following are the two patterns I was using to split the string "123.3+23+23.3" . 以下是我用来分割字符串"123.3+23+23.3"的两种模式。

[+/*-]

[+*-/]

For the first pattern I got the output as: 对于第一个模式,我的输出为:

123.3
23
23.3

For the second pattern I got the output as : 对于第二种模式,我的输出为:

123
3
23
23
3

I've no idea, why I am getting the different outputs. 我不知道为什么要得到不同的输出。 Please help me out. 请帮帮我。

Within a character class, - is a range operator (as in [af] is the same as [abcdef] ). 在字符类中, -是范围运算符(如[af][abcdef]相同)。 So if you want to include an actual - in your range, it must be the first or last character. 因此,如果您想在您的范围内添加实际字符-它必须是第一个或最后一个字符。

Therefore, your first example will match + / * - , while your second will match + / * - , . 因此,你的第一个例子将匹配+ / * -而你的第二个将匹配+ / * - , . .

在此处输入图片说明

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

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