Reputation: 2918
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.
Upvotes: 0
Views: 100
Reputation: 8018
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
Upvotes: 0
Reputation: 52205
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.
Upvotes: 2