能正則表達式提取嵌入的字符串中的值中提取正值,如用相同的字符串中前面所定義的可變模板?或者這是更好的Java處理?例如:「2012法拉利[F12] - 鴕鳥皮內飾[F12#OL] - 糖果紅色金屬[F12#3]」變量模板是遇到方括號時遇到的第一個字符串,例如「F12#OL」 [F12],和所希望的變量被該模板,例如的後續實例中發現'OL'和'3'。正則表達式從字符串
1
A
回答
0
既然你提的Java,我假設你正在使用的Java實現,Pattern。
Java的模式支持所謂反向引用,它可以用來匹配以前捕獲組匹配的相同的值。
可惜你不能從一個單一的捕獲組中提取多個值,所以你必須硬編碼的,你想匹配,如果你想用一個模式做這個模板的數量。
對於一個變量,它看起來是這樣的:
\[(.*?)\].*?\[\1#(.*?)\]
^^^^^ ^^^^^ variable
template ^^ back reference to whatever template matched
您可以添加更多可選的比賽由這樣的包裹他們可選的非捕獲組:
\[(.*?)\].*?\[\1#(.*?)\](?:.*?\[\1#(.*?)\])?(?:.*?\[\1#(.*?)\])?
^optional group ^another one
這將匹配以三個變量:
String s = "2012 Ferrari [F12] - Ostrich Leather interior [F12#OL] - Candy Red Metallic [F12#3]";
String pattern = "\\[(.*?)\\].*?\\[\\1#(.*?)\\](?:.*?\\[\\1#(.*?)\\])?(?:.*?\\[\\1#(.*?)\\])?";
Matcher matcher = Pattern.compile(pattern).matcher(s);
if (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
// prints F12, OL, 3, null
如果您需要匹配任意數量的變量,howev呃,你將不得不求助於在第一遍中提取模板,然後將其嵌入到第二種模式中:
// compile once and store in a static variable
Pattern templatePattern = Pattern.compile("\\[(.*?)\\]");
String s = "2012 Ferrari [F12] - Ostrich Leather interior [F12#OL] - Candy Red Metallic [F12#3]";
Matcher templateMatcher = templatePattern.matcher(s);
if (!templateMatcher.find()) {
return;
}
String template = templateMatcher.group(1);
Pattern variablePattern = Pattern.compile("\\[" + Pattern.quote(template) + "#(.*?)\\]");
Matcher variableMatcher = variablePattern.matcher(s);
while (variableMatcher.find()) {
System.out.println(variableMatcher.group(1));
}
+0
我需要的兩步法。很棒。謝謝你們倆! – MichaelS 2012-07-06 21:06:21
相關問題
- 1. 正則表達式從字符串
- 2. 正則表達式從字符串
- 3. 正則表達式從字符串
- 4. 正則表達式從字符串
- 5. 正則表達式從字符串
- 6. 正則表達式從字符串
- 7. 正則表達式從字符串
- 8. 正則表達式從字符串
- 9. 從字符串與正則表達式
- 10. 正則表達式從字符串
- 11. 正則表達式從字符串
- 12. 正則表達式從字符串
- 13. 正則表達式從字符串
- 14. 正則表達式 - 從字符串
- 15. 正則表達式從字符串
- 16. Vb.net正則表達式 - 從字符串
- 17. 正則表達式從字符串
- 18. 正則表達式從字符串
- 19. 正則表達式從字符串
- 20. 正則表達式從字符串
- 21. 正則表達式從字符串
- 22. 正則表達式從字符串
- 23. 正則表達式從字符串
- 24. 正則表達式從字符串
- 25. 正則表達式從字符串
- 26. 正則表達式正則表達式匹配字符串
- 27. 正則表達式的正則表達式的Java字符串
- 28. 正則表達式從字符串中提取子字符串
- 29. 從字符串到正則表達式到新字符串
- 30. 從大字符串提取字符串oracle正則表達式
您是否正在使用Java的正則表達式實現? – 2012-07-06 19:04:44