java - How to return the first chunk of either numerics or letters from a string? -



java - How to return the first chunk of either numerics or letters from a string? -

for example, if had (-> means return):

abc123afa5 -> abc 168dgff9g -> 168 1ggggg -> 1

how can in java? assume it's regex related i'm not great regex , not sure how implement (i thought have feeling 5-10 lines long, , think done in one-liner).

thanks

string mystring = "abc123afa5"; string extracted = mystring.replaceall("^([a-za-z]+|\\d+).*$", "$1");

view regex demo , live code demonstration!

to utilize matcher.group() , reuse pattern efficiency:

// class private static final pattern pattern = pattern.compile("^([a-za-z]+|\\d+).*$"); // method { string mystring = "abc123afa5"; matcher matcher = pattern.matcher(mystring); if(matcher.matches()) system.out.println(matcher.group(1)); }

note: /^([a-za-z]+|\d+).*$ , /^([a-za-z]+|\d+)/ both works in similar efficiency. on regex101 can compare matcher debug logs find out this.

java regex string

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -