简体   繁体   中英

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?

Eg.

"Linux_version"
"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"

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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