I’m not new to Java, but have not dealt with Regex and Patterns before. What I’m looking to do is take a string like
"Class: " + data1 + "\nFrom: " + data2 + " To: " + data3 + "\nOccures: " + data4 + " In: " + data5 + " " + data6;
and pull out only data_1 to data_n.
I appreciate any help.
Use this regex:
Explanation:
.+?will match any character for undefined times, but non-greedy.(), using brackets will create a group. A group is given an index starting by 1 (since group 0 is the entire match)So,
(.+?)will creates groups of any character.And what the matcher does, is searching for the whole pattern somewhere in the input string. But since you specified the format, we know exactly how your entire string is going to look like. The only thing you have to do is copy the format and replace the data you want to extract with “something” (
.+?), which you give an index by creating a group of it.Afterwards, the matcher will try to find the pattern (done by
matcher.find()) and you ask them what the content is of the groups 1 up to 6.