簡體   English   中英

如何從Java中的字符串中提取多個正則表達式匹配

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM