0

我有一系列这种格式的字符串:

Something_fromSomewhere
Something_fromSomewhere_ABC123
Something_fromSomewhere_DEF456
Something_fromSomewhereElse
Something_fromSomewhereElse_GHI123

我正在尝试像这样对它们进行分组...

Something_fromSomewhere
    Something_fromSomewhere_ABC123
    Something_fromSomewhere_DEF456

Something_fromSomewhereElse
    Something_fromSomewhereElse_GHI123

所以我想挑选出包含这种模式的字符串:

^[Any1]_from[Any2]$

但我只想挑选Any2不包含任何下划线的行。我怎样才能做到这一点?

(一旦我有了“根”元素,我就可以进行简单的字符串匹配来查找子元素。)

4

2 回答 2

0

Your pattern won't do what you think it does. It will match a single A, n, y or 1 character, followed by a literal _from, followed by a single A, n, y or 2 character. The start (^) and end ($) anchors around your string will also ensure the entire string must match the pattern, and not just a substring.

Perhaps you want a pattern like this:

^(.*)_from([^_]*)

This will match zero or more of any character, captured in group 1, followed by a literal _from, followed by zero or more of any character other than underscores, captured in group 2. It will also allow any other characters to follow the matched substring.

Or possibly this:

^([^_]*)_from([^_]*)

This will match zero or more of any character other than underscores, captured in group 1, followed by a literal _from, followed by zero or more of any character other than underscores, captured in group 2. It will also allow any other characters to follow the matched substring.

于 2013-09-13T02:35:30.550 回答
0

指定下划线以外的非空字符序列的方法是

[^_]+

当您将^符号放入字符类中时(这是可以通过方括号语法定义的一组字符的花哨名称),字符类被反转:它匹配该类中包含的所有内容,而不是匹配包含的内容.

在您的情况下,整体表达式如下所示:

^[^_]+_from[^_]+$
于 2013-09-13T02:36:25.907 回答