Home > Net >  Extract words from a String in java
Extract words from a String in java

Time:11-20

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

CodePudding user response:

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!

  • Related