簡體   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