如何使用正则表达式从字符串中提取子字符串?

How to extract substring from a string using regex?

我想从以下字符串中提取用户名和日期:

Syed Arafath on Jan 7, 2015
Capt.KSD on Dec 30, 2014
chakradharalasakani on Dec 29, 2014
mitesh0123 on Dec 18, 2014
Aparajita61@yahoo.in on Dec 3, 2014
123chetan on Oct 28, 2014

我想要输出如下:

Syed Arafath
Capt.KSD
chakradharalasakani
mitesh0123
Aparjita61@yahoo.co.in
Jan 7,2015
Dec 30, 2014
Dec 29,2014
Dec 18,2014
Dec 3, 2014
Oct 28, 2014

总而言之,我想将字符串 "Syed Arafath on Jan 7, 2015" 拆分为 2 个字符串,一个包含用户名,另一个包含日期。

\s+on\s+ 上拆分,你应该得到你想要的东西

查看演示。

https://regex101.com/r/tX2bH4/29

编辑:

使用\s+on\s+(?!.*\bon\b)

https://regex101.com/r/tX2bH4/30

如果您关心 Syed on Arafath too.The 前瞻确保拆分发生在最后一个 on

只需根据以下正则表达式拆分您的输入,

"\s+on\s+(?=\S+\s+\d{1,2},)"

代码:

String txt = "Syed on Arafath on Jan 7, 2015";
String[] parts = txt.split("\s+on\s+(?=\S+\s+\d{1,2},)");
System.out.println(Arrays.toString(parts));

输出:

[Syed on Arafath, Jan 7, 2015]
import java.util.regex.*;
Pattern p = Pattern.compile("(.*) on (.*)");
Matcher m = p.matches(input);
if( m.matches() ) {
    String username = m.group(1);
    String date = m.group(2);
} else {
    throw new Exception("Did not match expected pattern");
}

使用直接正则表达式优于拆分:

Matcher m = Pattern.compile("(.*) on .*").matcher(input);
m.matches();
System.out.println(m.group(1));

* 量词的 greedy 质量保证名称中出现的任何 on 都会被它抓取,只有 last 出现的 on 将与 on 文字匹配。

作为拆分的替代方法,您可以使用 replaceAll

    String name = s.replaceAll("(.*) on .*", "");
    String date = s.replaceAll(".*(\w{3} \d{1,2}, \d{4}).*", "");