Java-抓住两个字符串之间的所有字符串的最佳方法?(正则表达式?)

这个问题困扰了我很久了,但从本质上讲,我正在寻找最有效的方法来捕获两个String之间的所有String。


我已经使用了许多个月的方法是通过使用一堆临时索引,字符串,子字符串,这确实很麻烦。(为什么Java没有诸如此类的本地方法String substring(String start, String end)?


说我有一个字符串:


abcabc [pattern1]foo[pattern2] abcdefg [pattern1]bar[pattern2] morestuff


最终目标是输出foo和bar。(并稍后添加到JList中)


我一直在尝试将regex并入,.split()但没有成功。我已经尝试过使用*'s和.'s 语法,但我认为这并不是我的意图,特别是因为.split()只需要拆分一个参数。


否则,我认为另一种方法是使用Pattern和Matcher类?但是我对适当的程序真的很模糊。


慕容森
浏览 1015回答 3
3回答

明月笑刀无情

尝试这个:String str = "its a string with pattern1 aleatory pattern2 things between pattern1 and pattern2 and sometimes pattern1 pattern2 nothing";Matcher m = Pattern.compile(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Pattern.quote("pattern1")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "(.*?)"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + Pattern.quote("pattern2")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;).matcher(str);while(m.find()){&nbsp; &nbsp; String match = m.group(1);&nbsp; &nbsp; System.out.println(">"+match+"<");&nbsp; &nbsp; //here you insert 'match' into the list}它打印:> aleatory <> and <> <
打开App,查看更多内容
随时随地看视频慕课网APP