[英]Extract certain substring in Java
I have a sentence, which is:我有一句话,就是:
User update personal account ID from P150567 to A250356.
I want to extract the keywords " P10567
" from this sentence.我想从这句话中提取关键字“
P10567
”。
How do I extract data between the sentence using regex or string method?如何使用正则表达式或字符串方法在句子之间提取数据?
String method:字符串方法:
Use StringUtils.substringBetween()
of Apache Commons :使用Apache Commons 的
StringUtils.substringBetween()
:
public static void main(String[] args) { String sentence = "User update personal account ID from P150567 to A250356."; String id = StringUtils.substringBetween(sentence, "from ", " to"); System.out.println(id); }
Regex method:正则表达式方法:
Use regex from (.*) to
, the string surrounded by parentheses is called group(1)
, just extract it:使用正则表达式
from (.*) to
,括号内的字符串称为group(1)
,提取即可:
public static void main(String[] args) { String regex = "from (.*) to"; String sentence = "User update personal account ID from P150567 to A250356."; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(sentence); matcher.find(); System.out.println(matcher.group(1)); }
Consider this string:考虑这个字符串:
String s = “Hey Hello from Scaler”
If you want only a “Hello” substring in the output of your program then call the substring method with 4 as its startIndex and 9 as its endIndex as you want the part of the given string starting from index 0 and ending at index 8.如果您只需要程序输出中的“Hello”子字符串,则调用 substring 方法,将 4 作为其 startIndex,9 作为其 endIndex,因为您希望给定字符串的一部分从索引 0 开始到索引 8 结束。
String s_substring = s.substring(4, 9)
//s_substring will contain “Hello” which is substring of string s
read more about Using Substring Method in Java here在此处阅读有关在 Java 中使用子字符串方法的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.