开发者

Pattern for pulling strings out a string

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开发者_如何学Go pull out only data_1 to data_n.

I appreciate any help.


Use this regex:

Pattern pattern = Pattern.compile("Class: (.+?)\nFrom: (.+?) To: (.+?)\nOccures: (.+?) In: (.+?) (.+?)");
Matcher matcher = pattern.matcher(yourInputString);
if (matcher.find())
{
     String data1 = matcher.group(1);
     String data2 = matcher.group(2);
     String data3 = matcher.group(3);
     String data4 = matcher.group(4);
     String data5 = matcher.group(5);
     String data6 = matcher.group(6);
} else
{
    // String didn't match the specified format
}

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.


how about using split() with ":", then from the splitted String[] get string[2i+1] ? (i from 0)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜