简体   繁体   English

如何删除 Java 中字符串中最后一个数字之后的所有内容?

[英]How to delete everything after the last number in a String in Java?

If I have a String that consists of letters and numbers, how can I get rid of everything after the last number in the String?如果我有一个由字母和数字组成的字符串,我怎样才能摆脱字符串中最后一个数字之后的所有内容?

Example:例子:

  • banana_orange_62_34_wednesday would become banana_orange_62_34 banana_orange_62_34_wednesday会变成banana_orange_62_34
  • 1234_4564_www_6_j_1_rrrr would become 1234_4564_www_6_j_1 1234_4564_www_6_j_1_rrrr将变为1234_4564_www_6_j_1

I tried this so far:到目前为止我试过这个:

int endIndex = inputXMLFilename.lastIndexOf("\\d+");
inputXMLFilename = inputXMLFilename.substring(0, endIndex);

Use regex replace:使用正则表达式替换:

str = str.replaceAll("\\D+$", "");

What the regex means:正则表达式的含义:

  • \D means “non-digit” \D表示“非数字”
  • + means “one or more of the previous term, greedy (as much of the input as possible)” +表示“一个或多个前项,贪婪(尽可能多的输入)”
  • $ means “end of input” $表示“输入结束”

The $ anchors the match to the end, without which this would match (and delete) all non-digits. $将匹配锚定到末尾,否则它将匹配(并删除)所有非数字。


lastIndexOf() only works with plain text, not regex. lastIndexOf()仅适用于纯文本,不适用于正则表达式。

@Test
public void cutAfterLastDigit() {
    String s = "banana_orange_62_34_wednesday";

    Pattern pattern = Pattern.compile("^(.*\\d)");
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()) {
        System.out.println(matcher.group(0));
    }
}

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

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