[英]How to extract multiple regex matches from a string in java
如何形成正則表達式以從字符串中提取格式為$ {variable name}的變量
可以說我有一個像這樣的字符串:
hello ${ person } welcome to ${ university name}. you are enrolled in ${class}
我需要從字符串中提取這些
人
大學名稱
類
您可以使用此正則表達式獲取${...}
所有值:
\$\{ *([\w -]+) *\}
Java代碼:
Pattern p = Pattern.compile("\\$\\{ *([\\w -]+) *\\}");
使用Matcher
對象使用while(matcher.find()) {...}
代碼段來抓取所有組。
您還可以使用RegEx在$ {}中查找所有值
\\ B * \\ u0024 \\ {(\\ W \\ S *)\\} \\乙
其中u0024是Unicode中的$,並在regexplanet中進行測試
這是代碼示例:
Pattern pattern = Pattern.compile("\\b*\u0024\\{([\\w\\s]*)\\}\\B");
String data = ...//String to parse
Matcher matcher = pattern.matcher(data);
// check all occurrence
while (matcher.find()) {
...
}
你可以用這個
MessageFormat.format(str, list);
str = hello {1}歡迎來到{2}。 您已加入{3}
並且只需傳遞列表中的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.