【问题标题】:Getting text between special characters using Regex使用正则表达式获取特殊字符之间的文本
【发布时间】:2014-10-09 21:44:14
【问题描述】:

我正在尝试获取特殊字符“|”之间的单词格式为[a-z]+@[0-9]+

示例文本 -

||ABC@123|abc@123456||||||ABcD@12||

预期输出 -

ABC@123, abc@123456, ABcD@12

我正在使用的正则表达式

(?i)\\|[a-z]+@[0-9]+\\|

当我使用这个正则表达式时,我得到的输出是|ABC@123|

我做错了什么?有人可以帮我解决这个问题吗?

【问题讨论】:

  • 只需将split() 与“|”一起使用.
  • @TheLostMind | 是一个特殊的正则表达式字符,你需要转义它
  • @assylias - 我想过。但后来我想,他也可以使用"[|]" :P。所以,我没有提到"\\|"

标签: java regex string-matching


【解决方案1】:

您需要使用匹配的Lookaround,但不要将其包含在匹配项中。

(?<=\||^)[a-z]+@[0-9]+(?=\||$)

这里是regex101 online demo

示例代码:

String pattern = "(?i)(?<=\\||^)[a-z]+@[0-9]+(?=\\||$)";
String str = "|ABC@123|abc@123456|ABcD@12";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.println(m.group());
}

输出:

ABC@123
abc@123456
ABcD@12

Lookaheadlookbehind,统称为lookaround,是零长度断言。不同之处在于环视实际上匹配字符,但随后放弃匹配,只返回结果:匹配或不匹配。这就是为什么它们被称为“断言”。

Read more...

模式说明:

  (?<=                     look behind to see if there is:
    \|                       '|'
   |                        OR
    ^                        the beginning of the line
  )                        end of look-behind

  [a-z]+                   any character of: 'a' to 'z' (1 or more times)
  @                        '@'
  [0-9]+                   any character of: '0' to '9' (1 or more times)

  (?=                      look ahead to see if there is:
    \|                       '|'
   |                        OR
    $                         the end of the line
  )                        end of look-ahead

【讨论】:

    【解决方案2】:

    您不应该将| 放在您的模式中,否则它将被匹配。像在其他解决方案中一样使用查找运算符,或者只匹配 (demo):

    [a-z]+@\d+
    

    您还应该考虑拆分| 上的字符串,如here 所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2017-02-16
      相关资源
      最近更新 更多