Snehal Patel
Snehal Patel

Reputation: 1330

Split string in alphabet and number

Would anyone be able to assist me with some regex. I want to split the following string into alphabet and number.

Example String ns01sp0001 after split it should be

ns01sp and 0001.

I tried with below regex.

String array[] = str.split("[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");

For upper case it's return

[NS, 01, SP, 0001]

but for lower case it's return

[, 01, 0001] // not able to get alphabet.

is there any way to get output like

[NS01SP,0001] // if input = NS01SP0001
[ns01sp,0001] //if input = ns01sp0001.

Upvotes: 2

Views: 4223

Answers (1)

anubhava
anubhava

Reputation: 785008

You can use:

String tok[] = str.split("(?<=\\D)(?=\\d+\\b)");

RegEx Demo

Upvotes: 5

Related Questions