0

I have a string variable and want to extract a value from it.

String LB0001 = "LB0001"; 
String[] splitString = LB0001.split("LB(.*)"); 

What I was expecting is that splitString would contain two values, ["LB0001",["0001"]]. However the result is null. Why? I have checked the regex and seems to be correct.

I want to extract "0001". I can do it using other ways, but would like to know what I am doing wrong here.

0

2 Answers 2

2

The split method will split where ever the regular expression provided matches. In your case, the expression LB(.*) matches the provided string completely, thus you get nothing back.

If you want to get the number part, you can split on anything which is not a digit, like so: .split("\\D"). This should get you 1 element which contains 0001.

EDIT: If you want anything after LB you would need to use the Pattern and Matcher class. So basically something like so:

String str = "LB0001";
Pattern p = Pattern.compile("LB(.*?)");
Matcher m = p.matcher(str);
while(m.find())
    System.out.println(m.groups(1));

The above will make use of regular expressions to look for any text which follows LB. I have changed it from .* to .*? in case you have something like so: LB001LB333. The extra ? makes the expression non greedy.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I part understand however, i am using myregexp.com to test my regex. When testing on the site, the regex is split into two groups group 1, is the full string match and group 2 is anything after "LB" .Is there a function in java that would give me a similar result?
Thank you, i ended up doing something similar. Have marked as solution
0

try this

String LB0001 = "LB0001"; 
String[] splitStringAlpha = LB0001.split("[a-zA-Z]+");
System.out.println(splitStringAlpha[0]); 
String[] splitStringNum = LB0001.split("\\D");
System.out.println(splitStringNum[0]);

this should give you

LB
0001

1 Comment

\w stands for "word character", usually [A-Za-z0-9_], so LB0001.split("\\W"); return LB0001

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.