2

I want to split this regexp pattern 2 numbers-3 numbers-5 numbers and letter in two part. Numbers and "-" one array and the letters in the second array.

I been trying to figure it out for a while. Hoping I can get some help.

Here is an example

"12-123-12345A"    <----- the string 
// I want to split it such that it can be ["12-123-12345","A"]

I tried this

"\\d{2}-\\d{3}-\\d{5}" 
// that only give me ["", "A"]

and this

"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
// ["12", "-", "123", "-", "12345", "A"]

3 Answers 3

4

\D matches any non-digit character (including -). You'd better to use [^-\d] instead to exclude -.

String s = "12-123-12345A";
String parts[] = s.split("(?<=\\d)(?=[^-\\d])");
System.out.println(parts[0]); // 12-123-12345
System.out.println(parts[1]); // A

See a demo: http://ideone.com/emr1Kq

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

7 Comments

That work really well but I was wondering if i can restrict the format ? so "12-123-123A" will not make the split and just return an empty array.
@AirWick219, It seem like Matcher.find is more appropriate for you. See this: ideone.com/fsmvnE
Matcher would be great but split also is accounting for "12-123-12345" without the letter in this case I want it to return just ["12-123-12345"]
Thank you so much... Learned alot.. so i am guess "?" means optional. how about if the end letter is not just one but it can add on..."12-123-12345A" or "12-123-12345AA" or "12-123-12345Aaaaaa". like split letters and "-" to be group(1) and all the letters to be in group(2)
@AirWick219, Yes it is. It matches zero or one match of preceding part => optional
|
1

try this

String[] a = "12-123-12345A".split("(?<=\\d)(?=\\p{Alpha})");

Comments

0

(\d{2}-\d{3}-\d{5})(\w)

You can test it on this website

http://regexpal.com/

Here's the java code. note double slash in replace of slash \ --> \\

package com.company;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// http://stackoverflow.com/questions/22061614
public class Main {

    public static void main(String[] args) {
      Pattern regex = Pattern.compile("(\\d{2}-\\d{3}-\\d{5})(\\w)");
      Matcher matcher = regex.matcher("12-123-12345A");
      matcher.find();
      System.out.println(matcher.group(1));
      System.out.println(matcher.group(2));
    // write your code here
    }
}

2 Comments

I initially got a match for "^\d{2}-\d{3}-\d{5}" but i guess in java it's different ??
@AirWick219 Guess in java you need to make single slash into double slash. I added the code above

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.