我有一句话,是:
User update personal account ID from P150567 to A250356.
我想提取关键字" P10567
"从这句话。
如何使用正则表达式或字符串方法在句子之间提取数据?
答案 0 :(得分:2)
字符串方法:
使用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);
}
正则表达式方法:
使用正则表达式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));
}