[英]Java regex: multiple matches in positive lookahead and lookbehind
I have some strings like this 我有一些像这样的字符串
my {test} value
my { test } value
my { test } value
I need to create a regex that will get everything inside {}
without spaces. 我需要创建一个正则表达式,使
{}
内的所有内容都没有空格。
With the next pattern (?<=\\{)\\s*[a-zA-Z]+\\s*(?=})
I get the content of curly brackets but with spaces 使用下一个模式
(?<=\\{)\\s*[a-zA-Z]+\\s*(?=})
我得到大括号的内容但是有空格
If I put \\s*
to positive lookahead like this (?<=\\{\\s*)[a-zA-Z]+(?=\\s*})
I see next error 如果我把
\\s*
放到像这样的正向前瞻(?<=\\{\\s*)[a-zA-Z]+(?=\\s*})
我看到下一个错误
Unable to execute regular expression.
无法执行正则表达式。 java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 8 (?<={\\s*)[a-zA-Z]+(?=\\s*}) ^
java.util.regex.PatternSyntaxException:Look-behind组在索引8附近没有明显的最大长度(?<= {\\ s *)[a-zA-Z] +(?= \\ s *})^
Is it possible to achieve this without trim()
of every regex match? 是否有可能在没有每个正则表达式匹配的
trim()
的情况下实现这一点?
You don't need look ahead or look behind. 你不需要向前看或向后看。 Simple regex like this is enough,
像这样的简单正则表达式就够了,
\{\s*(.*?)\s*\}
Demo, https://regex101.com/r/REDmDT/2 (included some more sample strings) 演示, https://regex101.com/r/REDmDT/2 (包含更多示例字符串)
Like you said, "I need to create a regex that will get everything inside {} without spaces" 就像你说的那样,“我需要创建一个正则表达式,将所有内容都放在{}中,而不是空格”
This regex gives you everything within curley braces while excluding right /left spaces and preserving any spaces inside as it is. 这个正则表达式为你提供了curley括号内的所有内容,同时排除了右/左空格并保留了内部的任何空格。
Here is a java code demonstrating same. 这是一个演示相同的java代码。
public static void main(String[] args) throws IOException {
List<String> list = Arrays.asList("my {test} value", "my { test } value", "my { test } value",
"my { test hello I am } value", "my { testing 10 times } value");
Pattern p = Pattern.compile("\\{\\s*(.*?)\\s*\\}");
list.forEach(x -> {
Matcher m = p.matcher(x);
if (m.find()) {
System.out.println(x + " --> " + m.group(1));
}
});
}
This outputs, 这输出,
my {test} value --> test
my { test } value --> test
my { test } value --> test
my { test hello I am } value --> test hello I am
my { testing 10 times } value --> testing 10 times
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.