在<之间找到所有单词和>与正则表达式

时间:2015-05-08 12:28:34

标签: java regex

我想在字符串中找到<>之间的单词。

例如:

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));    
     }
  }
}

我在做什么错了?

3 个答案:

答案 0 :(得分: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

注意

如果您偏爱没有索引后引用的解决方案,以及&#34;环顾四周&#34;,您可以使用以下代码实现相同的目标:

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());
}

我个人认为后者在这种情况下不太可读。

答案 1 :(得分: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());
 }

答案 2 :(得分: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));
        }
    }