[英]Extract words from a String in java
我想从当前字符串中提取单词“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";
所以我将返回一个字符串列表 firstName lastName bookName price
您需要使用以下正则表达式: as (\w+)
请参阅regex101上的示例及其说明。
示例代码是:
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);
你可以在这里运行它。
在这里使用正则表达式可能会非常好,如果您不知道正则表达式是什么,请查看https://regexone.com/
https://betterprogramming.pub/introduction-to-regex-8c18abdd4f70
这里有一些代码可以解决这个问题
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);
}
}
如果您有任何问题,请走开! 正则表达式一开始可能有点吓人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.