1

I have the following String

 String str1 =   "Peter L. Douglas 04/02/1984 X1 X5 YY" ;

I need to get three separate strings as following

String str1_name = "Peter L. Douglas" ;
String str1_date = "04/02/1984" ;
String str1_nbr  = "3"  ;     // 3 is three elements after date , i.e. X1 X5 YY 

I am not sure how I could do this in the most efficient way , especially counting the elements after the date


Other possible Strings are

String str1 = "Alexander Evanston 05/02/1986 X5 YY" ;

Buras
  • 3,069
  • 28
  • 79
  • 126
  • What is the actual pattern of your strings? Will trailing elements always be two characters? You have not provided enough information. – PM 77-1 Apr 06 '14 at 00:29

2 Answers2

3

To obtain the three parts from your string, you can use

^([A-Za-z. ]+) ((?:[0-9]{2}/){2}[0-9]{4}) (.*)$

Regular expression visualization

Debuggex Demo

The name is is capture group 1, the date in 2, the "X" pieces in 3. This regex assumes the date is always valid. If you really need to ensure a proper date, you can read this answer I wrote about using regex to validate numeric ranges.

Also note that while you could use \d in place of [0-9], [0-9] is more universal, as \d can capture non-american numbers in .NET for example. More information here and here.


To get the number of "X" pieces, just split group three, and then count the resulting array elements:

int xPieceCount = matcher.group(3).split(" ").length();
Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
2

Try this one

Find the date pattern(DD/MM/YYYY) first then get others also as simple as it is.

    String str1 = "Peter L. Douglas 04/02/1984 X1 X5 YY";
    Pattern pt = Pattern.compile("\\d\\d/\\d\\d/\\d\\d\\d\\d");

    Matcher m = pt.matcher(str1);

    if (m.find()) {
        System.out.println(str1.substring(0, m.start()).trim());
        System.out.println(m.group());
        System.out.println(str1.substring(m.end()).trim().split("\\s+").length);
    }

output

Peter L. Douglas
04/02/1984
3
Braj
  • 46,415
  • 5
  • 60
  • 76