1

I have been trying to figure out how to match the pattern of my input string with this kind of string:

"xyz 123456789"

In general every time I have a input that has first 3 characters (can be both uppercase or lowercase) and last 9 are digits (any combination) the input string should be accepted.

So if I have i/p string = "Abc 234646593" it should be a match (one or two white-space allowed). Also it would be great if "Abc" and "234646593" should be stored in seperate strings.

I have seeing a lot of regex but do not fully understand it.

2
  • 2
    An introduction to regular expressions in Java can be found here: docs.oracle.com/javase/tutorial/essential/regex Commented Jun 24, 2012 at 5:42
  • You can not learn regexes from randomly looking at examples. Take the time for in depth learning in one language, and later adopt it to similar syntaxes in other languages. Commented Jun 24, 2012 at 8:39

1 Answer 1

4

Here's a working Java solution:

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

public class Regex {
  public static void main(String[] args) {
    String input = "Abc 234646593";

    // you could use \\s+ rather than \\s{1,2} if you only care that
    // at least one whitespace char occurs
    Pattern p = Pattern.compile("([a-zA-Z]{3})\\s{1,2}([0-9]{9})");
    Matcher m = p.matcher(input);
    String firstPart = null;
    String secondPart = null;
    if (m.matches()) {
      firstPart = m.group(1);  // grab first remembered match ([a-zA-Z]{3})
      secondPart = m.group(2); // grab second remembered match ([0-9]{9})
      System.out.println("First part: " + firstPart);
      System.out.println("Second part: " + secondPart);
    }
  }
}

Prints out:

First part: Abc
Second part: 234646593
Sign up to request clarification or add additional context in comments.

3 Comments

As a small note, with code like this, it is usually better /not/ to initialize firstPart and secondPart. That way, if you would accidently reference it later in the code without giving it a proper value, that error will be caught at compile time instead of runtime.
I picked \\s{1,2} because the question said "one or two white-space allowed", so I was being strict to show him how to do it. Normally I would use \\s+ if I only care that there is at least one whitespace char and then any number after that.
@midpeter444: I see, I was wrong. Now I ask myself why I didn't saw it, but that is of course not interesting for someone else, so I deleted my comment. Sorry.

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.