text1text2"; How to get an array, for example arr[0] = "text1"; a...">

Java array preg_match

Enter the line strng = "<title>text1</title><title>text2</title>"; How to get an array, for example

arr[0] = "text1";
arr[1] = "text2";

I try to use this, but the result is, not an array text1</title><title>text2

Pattern pattern = Pattern.compile("<title>(.*)</title>");
Matcher matcher = pattern.matcher(strng);
matcher.matches();
+3
source share
3 answers

Although I agree that using an XML / HTML parser is a better alternative to the general one , your script is simple to solve with a regex:

List<String> titles = new ArrayList<String>();
Matcher matcher = Pattern.compile("<title>(.*?)</title>").matcher(strng);
while(matcher.find()){
    titles.add(matcher.group(1));
}

Note the unwanted operator .*?and use matcher.find()instead matcher.matches().

Reference:

+8
source

It looks like you need a HTML/ parser XMLthat is created for these tasks.

, , (, ), matcher. find() ,

(?<=\\>)\\w+(?=\\<)

, - , , , HTML/XML.

0

XML, , XML, XML. , , JDOM.

If XML or HTML do not use try and use regular expressions because XML and HTML are not ordinary languages, and you cannot parse regular expressions successfully because they cannot maintain sufficient state. Just search for stackoverflow for more details. it appears constantly, and there is a lot of information on why not do it and why it won’t work.

0
source

Source: https://habr.com/ru/post/1793989/


All Articles