2015-05-08 81 views
4

我想從字符串中找到<>之間的詞。查找< and >與正則表達式之間的所有詞

例如:

String str=your mobile number is <A> and username is <B> thanks <C>; 

我想從字符串ABC得到。

我已經試過

import java.util.regex.*; 

public class Main 
{ 
    public static void main (String[] args) 
    { 
    String example = your mobile number is <A> and username is <B> thanks <C>; 
    Matcher m = Pattern.compile("\\<([^)]+)\\>").matcher(example); 
    while(m.find()) { 
     System.out.println(m.group(1));  
    } 
    } 
} 

出了什麼問題我在做什麼?

+0

你喜歡有一個與短程解決方案'<電話<'** ** 876-5432'>'或長響了'<'**我nymber是<876-5432**'>' – MaxZoom

回答

6

用下面的習慣和向後引用獲取值您ABC佔位符:

String example = "your mobile number is <A> and username is <B> thanks <C>"; 
//       ┌ left delimiter - no need to escape here 
//       | ┌ group 1: 1+ of any character, reluctantly quantified 
//       | | ┌ right delimiter 
//       | | | 
Matcher m = Pattern.compile("<(.+?)>").matcher(example); 
while (m.find()) { 
    System.out.println(m.group(1)); 
} 

輸出

A 
B 
C 

注意

如果你青睞有沒有索引的反向參考的解決方案,而「查找變通」,就可以達到同樣的用下面的代碼:

String example = "your mobile number is <A> and username is <B> thanks <C>"; 
//       ┌ positive look-behind for left delimiter 
//       | ┌ 1+ of any character, reluctantly quantified 
//       | | ┌ positive look-ahead for right delimiter 
//       | | | 
Matcher m = Pattern.compile("(?<=<).+?(?=>)").matcher(example); 
while (m.find()) { 
    // no index for back-reference here, catching main group 
    System.out.println(m.group()); 
} 

我個人覺得後者的可讀性在這種情況下。

+0

感謝工作般的魅力 – Bhavesh

+0

@Bhavesh不客氣! – Mena

1

您需要在否定字符類中使用><>[^)]+在你的正則表達式中匹配任何charcater,但不是),一次或多次。所以這也符合<>符號。

Matcher m = Pattern.compile("<([^<>]+)>").matcher(example); 
while(m.find()) { 
    System.out.println(m.group(1)); 
} 

OR

使用lookarounds。

Matcher m = Pattern.compile("(?<=<)[^<>]*(?=>)").matcher(example); 
while(m.find()) { 
    System.out.println(m.group()); 
} 
1

你能試試嗎?

public static void main(String[] args) { 
     String example = "your mobile number is <A> and username is <B> thanks <C>"; 
     Matcher m = Pattern.compile("\\<(.+?)\\>").matcher(example); 
     while(m.find()) { 
      System.out.println(m.group(1)); 
     } 
    } 
+0

它的工作原理,我試過了。但你可以簡化正則表達式:''<(.+?)>'' –

+0

感謝您的更新:) –

相關問題