我试图在不包含空格的两个%字符之间获取内容。
到目前为止,这就是我所拥有的:(?<=\%)(.*?)(?=\%)
我想我需要在某个地方使用\S。但我还是想不出怎么用它。通常有两种情况:
字符串应该是这样的:
占位符称为%Test%!现在您可以将它与实际占位符一起使用。但是,如果我使用更多%Test2%占位符,它将不再工作:/。%测试3%糟糕的原因!
发布于 2018-10-11 11:35:50
如果我正确地理解了你的问题,那么%(\w+)%就会帮你做。
String str = "The placeholder is called %Test%! Now you can use it with real placeholders. But if I use more %Test2% placeholders, it won't work anymore :/. %Test3% sucks cause of that!";
String regex = "%(\\w+)%";//or %([^\s]+)% to fetch more special characters
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}输出:
Test
Test2
Test3发布于 2018-10-11 11:32:44
你可以用
(?<=%)[^%\s]+(?=%)见regex演示。或者,如果您更喜欢捕获:
%([^%\s]+)%见另一个演示。
[^%\s]+部件匹配一个或多个既不是%也不是空格的字符。
String line = "The placeholder is called %Test%! Now you can use it with real placeholders. But if I use more %Test2% placeholders, it won't work anymore :/. %Test3% sucks cause of that!";
Pattern p = Pattern.compile("%([^%\\s]+)%");
Matcher m = p.matcher(line);
List<String> res = new ArrayList<>();
while(m.find()) {
res.add(m.group(1));
}
System.out.println(res); // => [Test, Test2, Test3]https://stackoverflow.com/questions/52759007
复制相似问题