使用正则表达式查找所有位于 < 和 > 之间的单词

5

我希望能够从一个字符串中找到尖括号<>之间的单词。

例如:

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

我现在做的有什么问题吗?

你更喜欢使用短范围的解决方案 <电话 <876-5432>> 还是长范围的解决方案 <我的号码是<876-5432>> - MaxZoom
3个回答

7
使用以下成语和反向引用来获取您的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

注意

如果您偏好不带索引反向引用和“look-arounds”的解决方案,则可以使用以下代码实现相同的效果:

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
您需要在否定字符类中使用><>。您的正则表达式中的[^)]+匹配除)之外的任何字符,一次或多次。因此,这也将匹配<>符号。
 Matcher m = Pattern.compile("<([^<>]+)>").matcher(example);
 while(m.find()) {
   System.out.println(m.group(1));
 }

使用前后断言。

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

它有效,我试过了。但你可以简化正则表达式为:<(.+?)> - Binkan Salaryman
感谢您的更新 :) - akhil_mittal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接