2 回答

TA貢獻1851條經驗 獲得超4個贊
如果我正確理解你的問題,那么%(\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

TA貢獻1859條經驗 獲得超6個贊
您可以使用
(?<=%)[^%\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]
添加回答
舉報