16

I have the String a="abcd1234" and I want to split this into String b="abcd" and Int c=1234. This Split code should apply for all king of input like ab123456 and acff432 and so on. How to split this kind of Strings. Is it possible?

0

10 Answers 10

35

You could try to split on a regular expression like (?<=\D)(?=\d). Try this one:

String str = "abcd1234";
String[] part = str.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);

will output

abcd
1234

You might parse the digit String to Integer with Integer.parseInt(part[1]).

Sign up to request clarification or add additional context in comments.

4 Comments

\D matches all non-digit characters, while \d matches all digit characters. ?<= is a positive lookbehind (so everything before the current position is asserted to be a non-digit character), ?= is a positive lookahead (so everything after the current position is asserted as a digit). Does this help?
@ConcurrentHashMap this regex will not work if a string like "ABC123DEF567".
@MohitTyagi That's correct, but this is a total different question than the OP had. If you want to find the correct regex, try to play around a little bit with github.com/gskinner/regexr.
How will we separate if we have , for example a,1,g,4,5,12,jh,49,mn?
4

You can do the next:

  1. Split by a regex like split("(?=\\d)(?<!\\d)")
  2. You have an array of strings with that and you only have to parse it.

1 Comment

"(?=\\d)(?<!\\d)" please explain this
3

Use a regular expression:

Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
Matcher m = p.matcher(string);
if (!m.find())
{ 
  // handle bad string
}
String s = m.group(1);
int i = Integer.parseInt(m.group(2));

I haven't compiled this, but you should get the idea.

Comments

2
String st = "abcd1234";
String st1=st.replaceAll("[^A-Za-z]", "");
String st2=st.replaceAll("[^0-9]", "");
System.out.println("String b = "+st1);
System.out.println("Int c = "+st2);

Output

String b = abcd
Int c = 1234

Comments

0

A brute-force solution.

String a = "abcd1234";
int i;
for(i = 0; i < a.length(); i++){
    char c = a.charAt(i);
    if( '0' <= c && c <= '9' )
        break;
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);

Comments

0
public static void main(String... s) throws Exception {
        Pattern VALID_PATTERN = Pattern.compile("([A-Za-z])+|[0-9]*");
    List<String> chunks = new ArrayList<String>();
    Matcher matcher = VALID_PATTERN.matcher("ab1458");
    while (matcher.find()) {
        chunks.add( matcher.group() );
    }
}

7 Comments

You're confusing your character class brackets [] with parentheses ().
@Javier: The patterns says: Any case letters and/or numbers
@Ravi: Sorry, I did not get you.
Your quantifier + should have been after () like ([A-Z]|[a-z])+ and letters could also have been clubbed together like [a-zA-Z]. First issue is a downright error. The second one just works better.
Actually, your regex just won't work. You have a | pipe before [0-9]+ making an OR between letters and numbers. You should withdraw this as a solution or fix it after testing properly.
|
0

Use regex "[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])" to split the sting by alphabets and numbers.

for e.g.

String str = "ABC123DEF456";

Then the output by using this regex will be :

ABC
123
DEF
456

1 Comment

Welcome to Stack Overflow. This question already has an accepted answer. Please provide more explanation to show how your answer is perhaps better or different than those already provided.
0

try with this:

String input_string = "asdf1234";
String string_output=input_string.replaceAll("[^A-Za-z]", "");
int number_output=Integer.parseInt(input_string.replaceAll("[^0-9]", ""));
System.out.println("string_output = "+string_output);
System.out.println("number_output = "+number_output);

Comments

0

You can add some delimiter characters to each group of symbols, and then split the string around those delimiters:

public static void main(String[] args) {
    String[][] arr = {
            split("abcd1234", "\u2980"),
            split("ab123456", "\u2980"),
            split("acff432", "\u2980")};

    Arrays.stream(arr)
            .map(Arrays::toString)
            .forEach(System.out::println);
    // [abcd, 1234]
    // [ab, 123456]
    // [acff, 432]
}
private static String[] split(String str, String delimiter) {
    return str
            // add delimiter characters
            // to non-empty sequences
            // of numeric characters
            // and non-numeric characters
            .replaceAll("(\\d+|\\D+)", "$1" + delimiter)
            // split the string around
            // delimiter characters
            .split(delimiter, 0);
}

See also: How to split a string delimited on if substring can be casted as an int?

Comments

0
public class MyClass {
public static void main(String args[]) {
  String a = "a1j2a3i4";
    int i;
    String str1="";
    String str2="";
    for(i = 0; i < a.length(); i++){
             char c = a.charAt(i);
                if( '0' <= c && c <= '9' )
                         str1=str1+c;
                if( 'a' <= c && c <= 'z' )
                         str2=str2+c;
       }
   System.out.println(str1);
   System.out.println(str2);
   }}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.