Reputation: 622
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.
Upvotes: 1
Views: 939
Reputation: 14624
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
Upvotes: 4