-3

Consider the following example. I would like to divide the String into two parts by the char 'T'

// input
String toDivideStr = "RaT15544";

// output
first= "RaT";
second = "15544";

I've tried this:

String[] first = toDivideStr.split("T",0);

Output:

first = "Ra"
second = "15544"

How do I achieve this?

baudsp
  • 4,076
  • 1
  • 17
  • 35
Gadhet
  • 5

4 Answers4

2

What you need to to, is locate the last "T", then split:

StringToD.substring(StringToD.lastIndexOf("T") + 1)
Dargenn
  • 372
  • 4
  • 11
1

You could use a positive lookahead to assert a digit and a positive lookbehind to assert RaT.

(?<=RaT)(?=\\d)

For example:

String str = "RaT15544";
for (String element : str.split("(?<=RaT)(?=\\d)"))
    System.out.println(element);

Regex demo | Java demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You can use positive look-ahead with split limit parameter for this. (?=\\d)

With only T in the split method parameter, what happens is the regex engine consumes this T. Hence the two string split that occurs doesn't have T. To avoid consuming the characters, we can use non-consumeing look-ahead.

(?=\\d) - This will match the first number that is encountered but it will not consume this number

public static void main(String[] args) {

    String s = "RaT15544";
    String[] ss = s.split("(?=\\d)", 2);
    System.out.println(ss[0] + " " + ss[1]);
}
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
0

The below regex can be used to split the alphabets and numbers separately.

String StringToD = "RaT15544";
String[] parts = StringToD.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(parts[0]);
System.out.println(parts[1]);
notionquest
  • 37,595
  • 6
  • 111
  • 105