I need to extract the extract this string as 2 document example test(s): testing
one is example and the other is testing ...please tell开发者_Go百科 me how can i extract it...
You can use String.split()
method to split the function to split words from sentence.
Example.
String sentence = "example tests(s): testing";
String[] words = sentence.split(" ");
for (String word: words) {
system.out.println(word);
}
Found the example here: http://blog.codebeach.com/2008/03/split-string-into-words-in-java.html
Generally, you want to first come up with a pattern to match your input. Once you do that, and if the pattern doesn't do it already, simply put (...)
brackets around the pattern that matches the part you're interested in. This creates what is called capturing groups.
With java.util.regex.Matcher
, you can get what each group captured using the group(int)
method.
References
- regular-expressions.info/Brackets for Capturing, Repeating a Capturing Group vs Capturing a Repeated Group
Example
Given this test string:
i have 35 dogs, 16 cats and 10 elephants
Then (\d+) (cats|dogs)
yields 2 match results (see on rubular.com)
- Result 1:
35 dogs
- Group 1 captures
35
- Group 2 captures
dogs
- Group 1 captures
- Result 2:
16 cats
- Group 1 captures
16
- Group 2 captures
cats
- Group 1 captures
精彩评论