[英]Splitting up a string by what matches and does not match the regex
我目前有一個程序,可以找到字符串中的所有正則表達式,但是對於其他部分,我需要與正則表達式匹配的部分和不匹配的部分。
因此,如果我有<h1> hello world </h1>
我希望能夠將其拆分為[ <h1>
, hello world
</h1>
]。
是否有人對如何解決這個問題有任何想法?
這是我的代碼,用於拆分字符串以找到正則表達式部分
ArrayList<String> foundTags = new ArrayList<String>();
Pattern p = Pattern.compile("<(.*?)>");
Matcher m = p.matcher(HTMLLine);
while(m.find()){
foundTags.add(m.group(0));
}
例如 :
String text = "testing<hi>bye</hi><b>bla bla!";
Pattern p = Pattern.compile("<(.*?)>");
Matcher m = p.matcher(text);
int last_match = 0;
List<String> splitted=new ArrayList<>();
while (m.find()) {
splitted.add(text.substring(last_match,m.start()));
splitted.add(m.group());
last_match = m.end();
}
splitted.add(text.substring(last_match));
System.out.println(splitted.toString());
打印[testing, <hi>, bye, </hi>, , <b>, bla bla!]
那是你要的嗎? 如果您不希望空元素,可以輕松修復該代碼以省略空元素:
while (m.find()) {
if(last_match != m.start())
splitted.add(text.substring(last_match,m.start()));
splitted.add(m.group());
last_match = m.end();
}
if(last_match != text.length())
splitted.add(text.substring(last_match));
請記住,正如評論中所指出的那樣:使用regex解析任意HTML / XML通常是一個壞主意。
您可以使用正則表達式分組功能來檢索匹配項的不同部分。 例如:
ArrayList<String> list = new ArrayList<String>();
Pattern p = Pattern.compile("(<.*?>)(.*)(<.*?>)");
Matcher m = p.matcher("<h1> Hello World </h1>");
while(m.find()){
list.add(m.group(1));
list.add(m.group(2));
list.add(m.group(3));
}
將為您提供所需的列表: ["<h1>", " Hello World ", "</h1>"]
。 請注意,組號0是完全匹配的表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.