[英]Extract String from a within a String using a Regular Expression
我有一個很大的String,其中包含一些標記,例如:
{codecitation class="brush: java; gutter: true;" width="700px"}
我需要收集長字符串中包含的所有標記。 我在此任務中發現的困難是所有標記都包含不同的參數值。 他們唯一的共同點是初始部分:
{codecitation class="brush: [VARIABLE PART] }
您是否有使用正則表達式收集Java中所有標記的建議?
使用模式匹配找到標記,如下所示。 我希望這將有所幫助。
String xmlString = "{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}efasf{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}";
Pattern pattern = Pattern.compile("(\\{codecitation)([0-9 a-z A-Z \":;=]{0,})(\\})");
Matcher matcher = pattern.matcher(xmlString);
while (matcher.find()) {
System.out.println(matcher.group());
}
我想您對畫筆特別感興趣:java; 和裝訂線:true; 部分。
也許此片段有助於:
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CodecitationParserTest {
public static void main(String[] args) {
String testString = "{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}";
Pattern codecitationPattern = Pattern
.compile("\\{codecitation class=[\"]([^\"]*)[\"][^}]*\\}");
Matcher matcher = codecitationPattern.matcher(testString);
Pattern attributePattern = Pattern
.compile("\\s*([^:]*): ([^;]*);(.*)$");
Matcher attributeMatcher;
while (matcher.find()) {
System.out.println(matcher.group(1));
attributeMatcher = attributePattern.matcher(matcher.group(1));
while (attributeMatcher.find()) {
System.out.println(attributeMatcher.group(1) + "->"
+ attributeMatcher.group(2));
attributeMatcher = attributePattern.matcher(attributeMatcher
.group(3));
}
}
}
}
codecitationPattern提取一個codecitation元素的class屬性的內容。 attributePattern提取第一個鍵和值以及其余鍵,因此您可以遞歸應用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.