【问题标题】:Regex to find strings contained between separators正则表达式查找分隔符之间包含的字符串
【发布时间】:2010-10-15 17:26:45
【问题描述】:

在本文中:

text text text [[st: aaa bbb ccc ddd eee fff]] text text text text [[st: ggg hhh iii jjj kkk lll mmm nnn]] 文本 文本 文本

我正在尝试获取 [[st: 和以 ]] 结尾之间的文本

我的程序应该输出:

aaa bbb ccc ddd eee fff (第一场比赛) ggg hhh iii jjj kkk \n lll mmm nnn(第二场比赛)

但我只能让它返回第一个 [[st: 和最后一个 ]],所以只有一个匹配而不是两个。有什么想法吗?

这是我的代码:

package com.s2i.egc.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegex {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String bodyText = "text text text [[st: aaa bbb ccc ddd eee fff]] text text text text [[st: ggg hhh iii jjj kkk\n lll mmm nnn]] text text text";

        String currentPattern = "\\[\\[st:.*\\]\\]";

        Pattern myPattern = Pattern.compile(currentPattern, Pattern.DOTALL);

        Matcher myMatcher = myPattern.matcher(bodyText);

        int i = 1;

        while (myMatcher.find()) {
          String match = bodyText.substring(myMatcher.start() + 5, myMatcher.end() - 3);
          System.out.println(match + " (match #" + i + ")");
          i++;
        }                           


    }

}

【问题讨论】:

    标签: java regex csv


    【解决方案1】:

    量词 *(0 或更大)默认是贪婪的,所以它匹配第二个 ]]。

    尝试更改为不情愿的模式匹配:

    String currentPattern = "\\[\\[st:.*?\\]\\]";
    

    【讨论】:

      【解决方案2】:

      星号应该使用惰性模式

      .*  
      

      改用:

      "\\[\\[st:.*?\\]\\]"
      

      【讨论】:

        【解决方案3】:

        为了完整起见,没有非贪婪星,您可以匹配开头的 [[st:,后跟任何非]字符,可能包括 ] 字符后跟非]字符的序列,最后是]]:

        \[\[st:([^\]]*(?:\][^\]]+)*)\]\]
        

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多