加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:02:14 所属栏目:百科 来源:网络整理
导读:我想在之间找到一个字.和来自一个字符串. 例如: String str=your mobile number is A and username is B thanks C; 我想从String获得A,B,C. 我试过了 import java.util.regex.*;public class Main{ public static void main (String[] args) { String examp
我想在<之间找到一个字.和>来自一个字符串.

例如:

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

我想从String获得A,B,C.

我试过了

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

我在做什么有什么问题?

解决方法

使用以下idiom和back-reference获取A,B和C占位符的值:

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

我个人觉得后者在这种情况下不太可读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读