-2

I have String = March2022 and I want to split it into two words March and 2022 but the March word keeps changing based on the month sometimes April or June as well the year sometimes 2023 or 2024, how can I split it to

String month = March
String year = 2022

or

String month = April
String year = 2024

thanks in advance

I tried

month.split("\[0-9\]")\[0\];
year.split("\[A-z\]")\[0\];

but does not work

azro
  • 53,056
  • 7
  • 34
  • 70
Pureé Ad
  • 1
  • 2

4 Answers4

1

You don't need a splitting code (with separator), but a matching one

String value = "March2022";
Matcher m = Pattern.compile("([a-zA-Z]+)(\\d+)").matcher(value);

if (m.find()) {
    String month = m.group(1);
    String year = m.group(2);
    System.out.println(month + "/" + year); // March/2022
}
azro
  • 53,056
  • 7
  • 34
  • 70
0

If I understand you correctly this is what you are looking for:

String date = "March2022";

String[] part = date.split("(?<=\\D)(?=\\d)");
String month = part[0];
String year = part[1];
Dewin
  • 72
  • 8
0

You can use a regular expresion to capture the month name and year:

String monthYear =  "March2022";
        
// Create pattern to match strings with the month name followed by the year
Pattern pattern = Pattern.compile("([A-Za-z]+)([0-9]+)");
        
// Applies the pattern to the String inputed
Matcher matcher = pattern.matcher(monthYear);

if (matcher.find()) {
    String month = matcher.group(1); // gets the value captured by the first brackets -> ([A-Za-z]+)
    String year = matcher.group(2); // gets the value captured by the second brackets -> ([0-9]+)
}

You can read further documentation here: https://www.w3schools.com/java/java_regex.asp

0

I would just like to point out that there's no real need for regular expressions here.

int index = 0;
while (index < monthYear.length() && !Character.isDigit(monthYear.charAt(index))) {
    ++index;
}
String month = monthYear.substring(0, index);
String year = monthYear.substring(index);

This will split "March2022" into "March" and "2022" or "November2023" into "November" and "2023" or "May2024" into "May" and "2024", etc.

If you don't care about the "Year 9999" problem, you can also just do:

String month = monthYear.substring(0, monthYear.length() - 4);
String year = monthYear.substring(monthYear.length() - 4);

Although this will throw if the string is empty, or only contains the month and the month is shorter than 4 characters (or, generally, if the string is shorter than 4 characters).

David Conrad
  • 15,432
  • 2
  • 42
  • 54