-
String method:
Use
StringUtils.substringBetween()
of Apache Commons: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
calledgroup(1)
, just extract it: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)); }
solved Extract certain substring in Java