gpt4 book ai didi

java - 正则表达式查找分隔符之间包含的字符串

转载 作者:行者123 更新时间:2023-12-01 16:41:58 24 4
gpt4 key购买 nike

在本文中:

text text text [[st: aaa bbb ccc ddd eee fff]] text texttext text [[st: ggg hhh iii jjj kkklll mmm nnn]] text text text

I'm trying to get the text between the [[st: and that ends with ]]

My program should output:

aaa bbb ccc ddd eee fff  (first match)ggg hhh iii jjj kkk \n lll mmm nnn(second match)

But I can only get it to return the first [[st: and the last ]], so there is just one match instead of two. Any ideas?

Here's my code:

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


}

}

最佳答案

量词 *(0 或更多)默认是贪婪的,因此它匹配第二个 ]]。

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

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

关于java - 正则表达式查找分隔符之间包含的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/686117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com