[英]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.