简体   繁体   English

从 java 中的字符串中提取单词

[英]Extract words from a String in java

I would like to extract a list of words that fall specific after the word "as " (space after as) from the current string.我想从当前字符串中提取单词“as”(as 后的空格)之后的特定单词列表。

"Select s.BOOK_ID as bookID,s.first_name as firstName, s.last_name as lastName , b.book_name as bookName , b.price as price  FROM STUDENTS s JOIN BOOKS b ON b.ID = s.BOOK_ID";

so I will return a list of string firstName lastName bookName price所以我将返回一个字符串列表 firstName lastName bookName price

You need to use the following regex: as (\w+)您需要使用以下正则表达式: as (\w+)

See an example and its explanation on regex101 .请参阅regex101上的示例及其说明。

The sample code is:示例代码是:

Matcher matcher = Pattern.compile("as (\\w+)")
                  .matcher("Select s.BOOK_ID as bookID,s.first_name as firstName, s.last_name as lastName , b.book_name as bookName , b.price as price  FROM STUDENTS s JOIN BOOKS b ON b.ID = s.BOOK_ID");
List<String> results = new ArrayList<String>();
while (matcher.find()) {
    results.add(matcher.group(1));
}
System.out.println(results);

You can run it here .你可以在这里运行它。

Here it can be very nice to use regex, If you don't know what regex is, check out https://regexone.com/在这里使用正则表达式可能会非常好,如果您不知道正则表达式是什么,请查看https://regexone.com/

https://betterprogramming.pub/introduction-to-regex-8c18abdd4f70 https://betterprogramming.pub/introduction-to-regex-8c18abdd4f70

Here are some code that can solve this problem这里有一些代码可以解决这个问题

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
class Main{
  public static void main(String[] args) {
    String s  = "Select s.BOOK_ID as bookID,s.first_name as firstName, s.last_name as lastName , b.book_name as bookName , b.price as price  FROM STUDENTS s JOIN BOOKS b ON b.ID = s.BOOK_ID";
    Pattern pattern = Pattern.compile("as (\\w+)"); //this is the regex pattern
    Matcher matcher = pattern.matcher(s); //this tries to match your string with the pattern
    ArrayList<String> arr = new ArrayList<>(); //arraylist to store the result
    while (matcher.find()) { //this makes it loop over all the matches it finds.
    arr.add(matcher.group(1)); //adds the SECOND match to the group. Try removing the number 1 and see the result after.

    }
    System.out.println(arr);
  }
}

If you have any questions, ask away!如果您有任何问题,请走开! Regex can be kinda scary in the start正则表达式一开始可能有点吓人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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