如果我正确理解你的问题,那么%(\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)); }输出:TestTest2Test3
您可以使用(?<=%)[^%\s]+(?=%)请参阅正则表达式演示。或者,如果您更喜欢捕获:%([^%\s]+)%请参阅另一个演示。该[^%\s]+部分匹配一个或多个既不%是空格也不是空格的字符。请参阅Java 演示: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]