Java preg_match数组 [英] Java preg_match array

查看:125
本文介绍了Java preg_match数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有字符串 strng =< title> text1< / title>< title> text2< / title>;
如何获得数组

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

我试着用这个,但结果是,而不是数组 text1< ; / title>< title> text2

  Pattern pattern = Pattern.compile(<标题><(*); /标题>中); 
匹配匹配器= pattern.matcher(strng);
matcher.matches();


解决方案

虽然我同意使用XML / HTML解析器< a href =http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html =noreferrertitle =如果您使用正则表达式来解析XML,Cthulhu会调用!!!>是一个更好的选择,一般情况下,你的场景很容易用正则表达式解决:

  List< ;字符串> titles = new ArrayList< String>(); 
匹配匹配器= Pattern.compile(< title>(。*?)< / title>)。 (matcher.find()){
titles.add(matcher.group(1));
}

请注意非贪婪算子。*?并使用 matcher.find()而不是 matcher.matches() p>

参考:
$ b


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();

解决方案

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:

这篇关于Java preg_match数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆