[英]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]+(?=\||$)
样例代码:
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
Lookahead
和lookbehind
,统称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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.