简体   繁体   English

如果Java中包含数字,请在字符串中拆分-但结果中要包含数字?

[英]Split a string in Java if it contains digit - but include digit in result?

I'm looking to split a string using Java if it contains a digit or underscore - but I want to include the digit in the result - is this possible? 我正在寻找使用Java拆分字符串的方式,如果该字符串包含数字或下划线-但我想在结果中包含数字-这可能吗?

Eg. 例如。

"Linux_version" “ Linux_version”
"Linux3.1.2.x" “ Linux3.1.2.x”

I want to split strings like these to get either "version" if it contains an underscore, or the digits to the end of the string if it contains a digit - eg from the second string above - I want "3.1.2.x" 我想分割这样的字符串以获取“版本”(如果它包含下划线),或者数字到字符串末尾(如果它包含数字),例如从上面的第二个字符串开始,我想要“ 3.1.2.x”

Any help is much appreciated! 任何帮助深表感谢!

expectedString = yourString.replaceAll("^[^_0-9]+_?","");

如果您只想删除LinuxLinux_ ,请尝试以下操作:

expectedString = yourString.replaceAll("(?i)^linux_?","")

此正则表达式替换将执行此操作:

input.replaceAll("^.*?((?<=_)|(?=\\d))", "");
String input = "Linux_version";
//String input = "Linux3.1.2.x";
String result = null;
Pattern p = Pattern.compile("_(.*)|(\\d.*)");
Matcher m = p.matcher();
if (m.find()){
  if (m.group(1) != null){
    result = m.group(1); //"version"
  } else if (m.group(2) != null){
    result = m.group(2); //"3.1.2.x"
  }
}

Can't help you with java code but I think you can use the following regex pattern; 无法帮助您使用Java代码,但我认为您可以使用以下正则表达式模式;

(_|[0-9])+[.a-zA-Z0-9]+ (_ | [0-9])+ [。a-zA-Z0-9] +

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

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