正则表达式在Java中搜索{{和}}之间的关键字
在Java中,在正则表达式在Java中搜索{{和}}之间的关键字,java,regex,regex-lookarounds,Java,Regex,Regex Lookarounds,在Java中,在{{和}之间搜索关键字的正则表达式是什么 示例String=“kksdkjhsd{{one}}sdkjhsdjksd{{{two}}” 我想要output=[“一”,“二] 我已经尝试过中建议的方法 它可以在单括号中使用,但我无法在双花括号({{})中扩展它 import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Patter
{{
和}
之间搜索关键字的正则表达式是什么
示例String=“kksdkjhsd{{one}}sdkjhsdjksd{{{two}}”
我想要output=[“一”,“二]代码>
我已经尝试过中建议的方法
它可以在单括号中使用,但我无法在双花括号({{}
)中扩展它
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static final String REGEX_START = Pattern.quote("{{");
public static final String REGEX_END = Pattern.quote("}}");
public static final Pattern PATTERN = Pattern.compile(REGEX_START + "(.*?)" + REGEX_END);
public static void main(String[] args) {
String input = "kksdkjhsd {{one}} sdkjhsdjksd {{two}}";
List<String> keywords = new ArrayList<>();
Matcher matcher = PATTERN.matcher(input);
// Check for matches
while (matcher.find()) {
keywords.add(matcher.group(1)); // Group one is necessary because of the brackets in the pattern
}
// Print
keywords.forEach(System.out::println);
}
}
此代码应符合您的要求:
Matcher m = Pattern.compile("\\{\\{([^\\}]*)\\}\\}").matcher(word);
while (m.find()){
System.out.println(m.group(1));
}
此正则表达式获取非}
字符的{{
}
中的所有文本。这个正则表达式不像{{{}}
那样处理大小写限制,在这种情况下返回{
,因为只有前两个{
匹配
如果您需要一个正则表达式,该正则表达式也匹配范围内的单个花括号,那么我们需要一个更复杂的解决方案
另一件事,使用字符类
([^\\}]*)
使正则表达式比(.*?
更有效,因为它会在第一个不是封闭的花括号的字符处停止搜索。您可以尝试使用regexp[{].[}][}]
。它使用不情愿的量词*?
,该量词匹配零个或多个字符,但采用非贪婪的方式,因此,一旦它开始匹配{
,它将在遇到的第一个}
处停止,而不是一直到字符串末尾并匹配最后一个}
作为一个有趣的额外功能,它可以匹配像
hey{{{{{}}you
,并生成how{}are
作为输出,而基于[^}]*
的regexp不能。将\{([^}]*}
扩展到\{([^}]*}}}
,您遇到了什么问题?
Matcher m = Pattern.compile("\\{\\{([^\\}]*)\\}\\}").matcher(word);
while (m.find()){
System.out.println(m.group(1));
}