我正試圖在Java中使用Regexes解析下列內容。Java正則表達式
我的測試字符串由內"${}"
如字符串爲前:"Test ${template} in ${xyz} : ${abc}"
我試圖使用窗體(\$\{[^\}]+\})
的正則表達式來匹配它。當前的正則表達式不匹配測試字符串中的任何內容。
如果我添加(.*?)(\$\{[^\}]+\})(.*?)
使其無法理解,那麼給我任何我想匹配的東西都是不一致的。
我的正則表達式有什麼問題?我如何解決它?
我正試圖在Java中使用Regexes解析下列內容。Java正則表達式
我的測試字符串由內"${}"
如字符串爲前:"Test ${template} in ${xyz} : ${abc}"
我試圖使用窗體(\$\{[^\}]+\})
的正則表達式來匹配它。當前的正則表達式不匹配測試字符串中的任何內容。
如果我添加(.*?)(\$\{[^\}]+\})(.*?)
使其無法理解,那麼給我任何我想匹配的東西都是不一致的。
我的正則表達式有什麼問題?我如何解決它?
您可能需要逃避括號,以及:
[email protected]:/usr/src/clusterFix$ python
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32)
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> s = 'Test ${template} in ${xyz} : ${abc}'
>>> re.compile('\$\{[^}]+\}').findall(s)
['${template}', '${xyz}', '${abc}']
很多時候有人問正則表達式的問題,我要求他們至少要考慮Commons Lang StringUtils時間:
String[] names = substringsBetween(theString, "${", "}");
不知道這一點,好的提示。 –
public static void main(String[] args) throws Exception {
String test = "Test ${template} in ${xyz} : ${abc}";
Matcher m = Pattern.compile("\\$\\{[^\\}]+\\}").matcher(test);
while (m.find())
System.out.println(m.group());
}
輸出:
${template}
${xyz}
${abc}
String test = "Test ${template} in ${xyz} : ${abc}";
Pattern p = Pattern.compile("\\$\\{[^}]+\\}");
Matcher matcher = p.matcher(test);
while (matcher.find()) {
System.out.println(matcher.group());
}
String ip="Test ${template} in ${xyz}";
Pattern p = Pattern.compile("\\{.*?\\}");
Matcher m =p.matcher(ip);
while(m.find())
{
System.out.println(m.group());
}
一個斜線是不夠的。你需要兩個斜線。
試試這個正則表達式:
\\$\\{.+\\}
它檢查與$ {和}周圍的文本字符串。這可以濾除空白字符串(${}
)以及任何未正確關閉的東西。
如果你想盈和後面檢查的文本,儘量.+\\$\\{.+\\}.+
我躲過了$和花括號。 – Sachin
like this「(。*?)(\\ $ \\ {[^ \\}] + \\})(。*?)」 – Sachin
您可以顯示準備運行的示例代碼嗎? –