Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java preg_match array

Tags:

java

html

regex

Have string strng = "<title>text1</title><title>text2</title>"; How to get array like

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

I try to use this, but in result have, and not array text1</title><title>text2

Pattern pattern = Pattern.compile("<title>(.*)</title>");
Matcher matcher = pattern.matcher(strng);
matcher.matches();
like image 455
dobs Avatar asked Apr 21 '26 04:04

dobs


1 Answers

While I agree that using an XML / HTML parser is a better alternative in general, your scenario is simple to solve with 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 non-greedy operator .*? and use of matcher.find() instead of matcher.matches().

Reference:

  • Pattern > Reluctant Quantifiers
  • Matcher.find()
like image 112
Sean Patrick Floyd Avatar answered Apr 22 '26 17:04

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!