正则表达式,用于在一个表达式中选择子字符串

时间:2014-10-16 14:09:19

标签: regex

我有以下字符串:

bla bla XX_XXX = 999 OR XX _ XXX = 890 OR XX _X XX = 789 OR XX_ XX = 123

我想要检索XX_XXX XX _ XXX XX _X XX {{1 }}

我可以使每个单独工作,但不是一次性在一个正则表达式中。这可能吗?怎么样?

3 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式:

/[A-Z]+\s*_(?:\s*[A-Z])+/

上述模式将匹配X s后跟一个或多个

  • 空格/下划线后跟X s。

regex101 demo

答案 1 :(得分:0)

我想你想要这样的东西,

(?<=\s|^)[A-Z][A-Z]\s*_(?:\s*[A-Z])+

DEMO

<强>解释

                         '  '
(?<=                     look behind to see if there is:
  \s                       whitespace (\n, \r, \t, \f, and " ")
 |                        OR
  ^                        the beginning of the string
)                        end of look-behind
[A-Z]                    any character of: 'A' to 'Z'
[A-Z]                    any character of: 'A' to 'Z'
\s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                         more times)
_                        '_'
(?:                      group, but do not capture (1 or more
                         times):
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                           or more times)
  [A-Z]                    any character of: 'A' to 'Z'
)+                       end of grouping

答案 2 :(得分:0)

你可能需要这样的东西:

([A-Z]\s?){2}_(\s?[A-Z]){2,3}

使用您的符号,这会将XX_XXXX_XXX与任意两个字符之间的可选空白字符匹配。

Demo