简体   繁体   中英

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.

"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

You need to use the following regex: as (\w+)

See an example and its explanation on 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://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

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