简体   繁体   English

正则表达式Java正则表达式以提取除最后一个数字以外的字符串

[英]Regex java a regular expression to extract string except the last number

How to extract all characters from a string without the last number (if exist ) in Java, I found how to extract the last number in a string using this regex [0-9.]+$ , however I want the opposite. 在Java中,如何从不包含最后一个数字(如果存在)的字符串中提取所有字符,我发现了如何使用此正则表达式[0-9.]+$提取字符串中的最后一个数字,但是我想要相反的操作。

Examples : 例子 :

abd_12df1231 => abd_12df abd_12df1231 => abd_12df

abcd => abcd abcd => abcd

abcd12a => abcd12a abcd12a => abcd12a

abcd12a1 => abcd12a abcd12a1 => abcd12a

What you might do is match from the start of the string ^ one or more word characters \\w+ followed by not a digit using \\D 您可能要做的是从字符串^的开头开始匹配一个或多个单词字符\\w+然后使用\\D而不是数字

^\\w+\\D

As suggested in the comments, you could expand the characters you want to match using a character class ^[\\w-]+\\D or if you want to match any character you could use a dot ^.+\\D 如注释中所建议,您可以使用字符类^[\\w-]+\\D扩展要匹配的字符,或者如果要匹配任何字符,则可以使用点^.+\\D

If you want to remove one or more digits at the end of the string, you may use 如果要删除字符串末尾的一位或多位数字,则可以使用

s = s.replaceFirst("[0-9]+$", ""); 

See the regex demo 正则表达式演示

To also remove floats, use 要同时去除浮子,请使用

s = s.replaceFirst("[0-9]*\\.?[0-9]+$", ""); 

See another regex demo 查看另一个正则表达式演示

Details 细节

  • (?s) - a Pattern.DOTALL inline modifier (?s) Pattern.DOTALL内联修饰符
  • ^ - start of string ^ -字符串开头
  • (.*?) - Capturing group #1: any 0+ chars other than line break chars as few as possible (.*?) -捕获组#1:除换行符以外的任何0+个字符都尽可能少
  • \\\\d*\\\\.?\\\\d+ - an integer or float value \\\\d*\\\\.?\\\\d+ -整数或浮点值
  • $ - end of string. $ -字符串结尾。

Java demo : Java演示

List<String> strs = Arrays.asList("abd_12df1231", "abcd", "abcd12a", "abcd12a1", "abcd12a1.34567");
for (String str : strs)
    System.out.println(str + " => \"" + str.replaceFirst("[0-9]*\\.?[0-9]+$", "") + "\"");

Output: 输出:

abd_12df1231 => "abd_12df"
abcd => "abcd"
abcd12a => "abcd12a"
abcd12a1 => "abcd12a"
abcd12a1.34567 => "abcd12a"

To actually match a substring from start till the last number, you may use 要从开始到最后一个数字实际匹配子字符串,可以使用

(?s)^(.*?)\d*\.?\d+$

See the regex demo 正则表达式演示

Java code: Java代码:

String s = "abc234 def1.566";
Pattern pattern = Pattern.compile("(?s)^(.*?)\\d*\\.?\\d+$");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
    System.out.println(matcher.group(1)); 
} 

With this Regex you could capture the last digit(s) 使用此正则表达式,您可以捕获最后一个数字

\d+$

You could save that digit and do a string.replace(lastDigit,""); 您可以保存该数字并做一个string.replace(lastDigit,"");

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

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