-1

I want to extract the user name and the date from the following string:

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

I want the output as follows:

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

In all I want to split the string "Syed Arafath on Jan 7, 2015" into 2 strings, one containing the username and the other containing the date.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • possible duplicate of [Learning Regular Expressions](http://stackoverflow.com/questions/4736/learning-regular-expressions) – Andy Brown Jan 16 '15 at 13:31

5 Answers5

4

Do a split on \\s+on\\s+ and you should get what you want

See demo.

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

EDIT:

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

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

If you care about Syed on Arafath too.The lookahead makes sure split occurs on the last on .

vks
  • 67,027
  • 10
  • 91
  • 124
1

Just split your input according to the below regex,

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

Code:

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));

Output:

[Syed on Arafath, Jan 7, 2015]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
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");
}
Nicholas Daley-Okoye
  • 2,267
  • 1
  • 18
  • 12
0

Using a direct regex is preferrable to splitting:

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

The greedy quality of the * quantifier guarantees that any occurrence of on within the name will be grabbed by it and only the last occurence of on will be matched by the on literal.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

As an alternative to split you can use replaceAll

    String name = s.replaceAll("(.*) on .*", "$1");
    String date = s.replaceAll(".*(\\w{3} \\d{1,2}, \\d{4}).*", "$1");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275