-1

I have a string, like

12abcdef
1ab2cdef
abcdef

string can start with number or without number but I need to split it into two parts, first number(if any) and second string

I need to split the string as [12,abcdef] [1,ab2cdef][abcdef]

How can I do this in java? which regex expression should I use with spilit in java?

user8937225
  • 27
  • 2
  • 4

4 Answers4

0

Use a regex with capturing groups, and a Matcher, like this:

String s = "12abcdef";
Pattern p = Pattern.compile("([0-9]*)([^0-9]*)");
Matcher m = p.matcher(s);
if (m.matches()){
    System.out.println("Digits = \"" + m.group(1) + "\"");
    System.out.println("Non-digits = \"" + m.group(2) + "\"");
} else 
    System.out.println("No match");
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21
0

There are lots of ways to solve this, split is a good starter. Here is a working example which will handle your user case.

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println(splitString("12abcdef"));
        System.out.println(splitString("1ab2cdef"));
        System.out.println(splitString("abcdef"));
    }

    private static String splitString(String string) {
        String[] split = string.split("[a-z]");

        return split.length >= 1 ? split[0] : "";
    }
}

This will return either the numbers, or a blank string if no numbers.

Chris
  • 3,437
  • 6
  • 40
  • 73
0

Here is what you exactly want using java regex:

public class SplitNumStr {
    private final static Pattern NUM_STR_PATTERN = Pattern.compile("(\\d+)(\\w+)");
    public static void main(String... args) {
        List<String> list = new ArrayList<>(Arrays.asList("12absc", "2bbds", "abc"));
        for (String s : list) {
            System.out.println(Arrays.toString(split(s)));
        }
    }

    private static String[] split(String numStr) {
        Matcher matcher = NUM_STR_PATTERN.matcher(numStr);
        if (matcher.find()) {
            return new String[] {matcher.group(1), matcher.group(2)};
        } else return new String[] { numStr };
    }
}

And the output:

[12, absc]
[2, bbds]
[abc]
Hearen
  • 7,420
  • 4
  • 53
  • 63
-1

Just count the continuous numbers and use String.substring.

static String[] test(String s) {
    int e = 0;
    while (e < s.length() 
        && '0' <= s.charAt(e)
        && s.charAt(e) <= '9')
        e++;
    return e == 0 || e == s.length() ? 
        new String[] { s } : 
        new String[] { s.substring(0, e), s.substring(e) };
}
zhh
  • 2,346
  • 1
  • 11
  • 22