简体   繁体   English

Java正则表达式不起作用-字符串拆分

[英]Java regex not working - string split

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"]] . 我期望的是splitString将包含两个值["LB0001",["0001"]] However the result is null. 但是结果为空。 Why? 为什么? I have checked the regex and seems to be correct. 我检查了正则表达式,似乎是正确的。

I want to extract "0001". 我想提取“ 0001”。 I can do it using other ways, but would like to know what I am doing wrong here. 我可以使用其他方法来完成此操作,但想知道我在这里做错了什么。

The split method will split where ever the regular expression provided matches. split方法将在提供的正则表达式匹配的地方进行拆分。 In your case, the expression LB(.*) matches the provided string completely, thus you get nothing back. 在您的情况下,表达式LB(.*)完全匹配提供的字符串,因此您一无所获。

If you want to get the number part, you can split on anything which is not a digit, like so: .split("\\\\D") . 如果要获取数字部分,可以拆分任何非数字的内容,例如: .split("\\\\D") This should get you 1 element which contains 0001 . 这应该给您1个元素,其中包含0001

EDIT: If you want anything after LB you would need to use the Pattern and Matcher class. 编辑:如果您想在LB之后获得任何东西 ,则需要使用PatternMatcher类。 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 . 上面将使用正则表达式来查找LB任何文本。 I have changed it from .* to .*? 我已将其从.*更改为.*? in case you have something like so: LB001LB333 . 如果您有类似的东西: LB001LB333 The extra ? 额外的? makes the expression non greedy. 使表达不贪心。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM