簡體   English   中英

正則表達式提取兩個字符之間的字符串

[英]regex extract string between two characters

我想使用Java中的regex提取給定字符串中以下字符之間的字符串:

/*
1) Between \" and \"   ===> 12222222222
2) Between :+ and @    ===> 12222222222
3) Between @ and >     ===> 192.168.140.1
*/

String remoteUriStr = "\"+12222222222\" <sip:+12222222222@192.168.140.1>";
String regex1 = "\"(.+?)\"";
String regex2 = ":+(.+?)@";
String regex3 = "@(.+?)>";

Pattern p = Pattern.compile(regex1);
Matcher matcher = p.matcher(remoteUri);
if (matcher.matches()) {
    title = matcher.group(1);
}

我正在使用上面給定的代碼片段,它無法提取我想要的字符串。 我做錯了嗎? 同時,我對regex還是很陌生。

matches()方法嘗試將正則表達式與整個字符串匹配。 如果要匹配字符串的一部分,則需要find()方法:

if (matcher.find())

但是,您可以構建一個正則表達式來一次匹配所有三個部分:

String regex = "\"(.+?)\" \\<sip:\\+(.+?)@(.+?)\\>";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(remoteUriStr);
if (matcher.matches()) {
    title = matcher.group(1);
    part2 = matcher.group(2);
    ip = matcher.group(3);
}

演示: http//ideone.com/8t2EC

如果您的輸入看起來總是這樣,並且始終希望輸入相同的部分,則可以將其放在單個正則表達式中(具有多個捕獲組):

"([^"]+)" <sip:([^@]+)@([^>]+)>

這樣您就可以使用

Pattern p = Pattern.compile("\"([^\"]+)\" <sip:([^@]+)@([^>]+)>");
Matcher m = p.matcher(remoteUri);
if (m.find()) {
  String s1 = m.group(1);
  String s2 = m.group(2);
  String s3 = m.group(3);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM