Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

regex for String and Number

SreramSep 12 2014 — edited Sep 12 2014

Hi,

Am trying to write a regular expression for a text which has both String and number... like abc1234, xyz987, gh1052 etc. And the string usually contains 2 or 3 characters.

What i need is two Strings one containing the text (abc, xyz, gh etc) and other containing number (1234, 987, 1052, etc.). Have written the code below. but doesn't seem to work. Any ideas?

String query = "abc1052"; //Or query = "zyx900";

String regexp = "(.{3})(\\d*)|(.{2}(\\d*))";

Pattern pattern = Pattern.compile(regexp);

Matcher match = pattern.matcher(query);

if(match.find()){

    System.out.println("Count: " + match.groupCount());

    for(int iter = 0; iter <= match.groupCount(); iter++){

        System.out.println("match" + iter + ": " + match.group(iter));

    }

} else {

        System.out.println("No match!!!");

}

Also tried with regexp = "(.\\s*)(.\\d*)" in no avail.

Finally achieved with regexp = "(\\D*)(\\d*)"; Thanks

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 10 2014
Added on Sep 12 2014
1 comment
804 views