java正则 提取两个字符串中间的字段

2024-11-02 01:22:46
推荐回答(2个)
回答1:

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

public class Cat
{
public static void main(String[] args)
{
String str = "asdf_{asd}_fas_{dfa}_sdfasdf_{dfa}_ ";
String reg = "_\\{((?:(?!\\}_)[\\s\\S])*)\\}_";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(str);
while(matcher.find())
{
System.out.println(matcher.group(1));
}
}
}

回答2:

Pattern pattern = Pattern.compile("_\\{(.*?)\\}_");
Matcher matcher = pattern.matcher("asdf_{asd}_fas_{dfa}_sdfasdf_{dfa}_");
while(matcher.find()){
    System.out.println(matcher.group(1));
}