简体   繁体   中英

how can i extract using regex in java

我需要将提取的字符串提取为2个文档example test(s): testing一个为示例,另一个为测试...请告诉我如何提取它...

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM