This question has been bugging me for a long time now but essentially I’m looking for the most efficient way to grab all Strings between two Strings.
The way I have been doing it for many months now is through using a bunch of temporary indices, strings, substrings, and it’s really messy. (Why does Java not have a native method such as String substring(String start, String end)?
Say I have a String:
abcabc [pattern1]foo[pattern2] abcdefg [pattern1]bar[pattern2] morestuff
The end goal would be to output foo and bar. (And later to be added into a JList)
I’ve been trying to incorporate regex in .split() but haven’t been successful. I’ve tried syntax using *‘s and .‘s but I don’t think it’s quite what my intention is especially since .split() only takes one argument to split against.
Otherwise I think another way is to use the Pattern and Matcher classes? But I’m really fuzzy on the appropriate procedure.
You can construct the regex to do this for you:
This will treat the
pattern1andpattern2as literal text, and the text in between the patterns is captured in the first capturing group. You can removePattern.quote()if you want to use regex, but I don’t guarantee anything if you do that.You can add some customization of how the match should occurs by adding flags to the
regexString.(?iu)at the beginning ofregexString, or supplyPattern.CASE_INSENSITIVE | Pattern.UNICODE_CASEflag toPattern.compilemethod.(?s)before(.*?), i.e."(?s)(.*?)", or supplyPattern.DOTALLflag toPattern.compilemethod.Then compile the regex, obtain a
Matcherobject, iterate through the matches and save them into aList(or anyCollection, it’s up to you).Testing code:
Do note that if you search for the text between
fooandbarin this inputfoo text foo text bar text barwith the method above, you will get one match, which istext foo text.