繁体   English   中英

使用正则表达式在特殊字符之间获取文本

[英]Getting text between special characters using Regex

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

示范文本 -

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

预期产量-

ABC@123, abc@123456, ABcD@12

我正在使用的正则表达式

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

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

我在做什么错? 有人可以帮我吗?

您需要使用相匹配的环顾四周 ,但不要将其包含在匹配中。

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

这是regex101在线演示

样例代码:

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 ,是零长度的断言。 区别在于,环顾四周实际上是匹配字符,但随后放弃了匹配,仅返回结果:匹配或不匹配。 这就是为什么它们被称为“断言”的原因。

阅读更多...

模式说明:

  (?<=                     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

你不应该把| 按照您的模式,否则它将被匹配。 与其他解决方案一样,使用lookaraound运算符,或者仅匹配( demo ):

[a-z]+@\d+

您还应该考虑在|上拆分字符串。 这里所示

暂无
暂无

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

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