本文介绍了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解析器是一个更好的选择,一般情况下,你的场景很容易用正则表达式解决: List< ;字符串> titles = new ArrayList< String>(); 匹配匹配器= Pattern.compile(< title>(。*?)< / title>)。 (matcher.find()){ titles.add(matcher.group(1)); } 请注意非贪婪算子。*?并使用 matcher.find()而不是 matcher.matches() p> 参考: $ b 模式>不情愿的量词 Matcher.find() Have string strng = "<title>text1</title><title>text2</title>";How to get array likearr[0] = "text1";arr[1] = "text2";I try to use this, but in result have, and not array text1</title><title>text2Pattern 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:Pattern > Reluctant QuantifiersMatcher.find() 这篇关于Java preg_match数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 05:53