开发者

how can i extract using regex in java

开发者 https://www.devze.com 2023-01-11 04:24 出处:网络
I need to extract the extract this string as 2 documentexample   test(s): testing one is example and the other is testing ...please tell开发者_Go百科 me how can i extract it...You can use String.spli

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
  • Result 2: 16 cats
    • Group 1 captures 16
    • Group 2 captures cats
0

精彩评论

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

关注公众号