Java 替换字符串的最后一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1660034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:47:32  来源:igfitidea点击:

Replace last part of string

javaregexstringreplace

提问by Harish

I want to replace the last String which is a ,with )

我想,以取代过去的字符串,它是一个,)

Suppose the string is:

假设字符串是:

Insert into dual (name,date,

插入对偶(姓名、日期、

to be converted to:

要转换为:

Insert into dual (name,date)

插入对偶(姓名,日期)

采纳答案by jjnguy

The following code should replace the last occurrence of a ','with a ')'.

下面的代码应该用 a 替换最后一次出现的','a ')'

StringBuilder b = new StringBuilder(yourString);
b.replace(yourString.lastIndexOf(","), yourString.lastIndexOf(",") + 1, ")" );
yourString = b.toString();

NoteThis will throw Exceptions if the Stringdoesn't contain a ','.

注意如果String不包含 ,这将抛出异常','

回答by Dani

Check the length of the string, check the last char (if you have the length it is easy) and replace it - when necessary. This solution is not lang. specific. just use a common sense.

检查字符串的长度,检查最后一个字符(如果你有长度很容易)并替换它 - 必要时。这个解决方案不是lang。具体的。只是使用常识。

回答by sfussenegger

str = str.substring(0, str.lastIndexOf(",")) + ")";

回答by NawaMan

You can use regular expression:

您可以使用正则表达式:

String aResult = "Insert into dual (name,date,".replaceAll(",$", ")");

replaceAll(...)will match string string with the given regular expression (parameter 1) (in this case we match the last character if it is a comma). The replace it with a replacement (parameter 2) (in this case is ')').

replaceAll(...)将字符串字符串与给定的正则表达式(参数 1)匹配(在这种情况下,我们匹配最后一个字符,如果它是逗号)。将其替换为替换(参数 2)(在本例中为“ )”)。

Plus!If you want to ensure that tailing spaces and tabs are taken care of, you can just change the regex to ',\[ \t\]*$'. NOTE '\[' and '\]' is without backslash (I don't know how to properly escape it).

加!如果要确保处理尾随空格和制表符,只需将正则表达式更改为“ ,\[ \t\]*$”。注意 ' \[' 和 ' \]' 没有反斜杠(我不知道如何正确转义它)。

Hope this helps.

希望这可以帮助。

回答by ty812

The more readable way ... Which you can use to learn about String and its' functions

更具可读性的方式......您可以使用它来了解 String 及其函数

String myString = "Insert into dual (name,date,";
String newString = "";
int length = myString.length();
String lastChar = myString.substring(length-1);

if (lastChar.contains(",")) {
    newString = myString.substring(0,length-1) + ")";
} 

System.out.println(newString);

回答by Ivan Caderno

This is a custom method to replace only the last substring of a given string. It would be useful for you:

这是一种自定义方法,用于仅替换给定字符串的最后一个子字符串。这对你有用:

private String replaceLast(String string, String from, String to) {
     int lastIndex = string.lastIndexOf(from);
     if (lastIndex < 0) return string;
     String tail = string.substring(lastIndex).replaceFirst(from, to);
     return string.substring(0, lastIndex) + tail;
}

回答by Muhammad Gelbana

Try this regex (^.+)b(.+$)

试试这个正则表达式 (^.+)b(.+$)

Example (Replace the last bcharacter)

示例(替换最后一个b字符)

System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", ""));

回答by ralphgabb

whats up with the hassle if you can just do this

如果你能做到这一点,麻烦怎么办

word = (String) word.subSequence(0, word.length() -1);

this returns new String without the last part of a String.

这将返回没有字符串最后一部分的新字符串。

回答by Se Song

TO replace a last char of your string by )

将字符串的最后一个字符替换为 )

str = str.substring(0, str.length()-1)+")";

str = str.substring(0, str.length()-1)+")";

Make sure your string is not empty or null.

确保您的字符串不为空或 null。

回答by matttrach

On a similar search I found this answer:

在类似的搜索中,我找到了这个答案:

https://stackoverflow.com/a/37066403/875282

https://stackoverflow.com/a/37066403/875282

I think it is the best because it uses the java methods as intended rather than trying to reinvent the wheel. It essentially reads the string backwards and uses the String object's replaceFirst method, this is exactly what I was looking for.

我认为它是最好的,因为它按预期使用 java 方法,而不是试图重新发明轮子。它本质上是向后读取字符串并使用 String 对象的 replaceFirst 方法,这正是我正在寻找的。

Here is the documentation on replaceFirst String method and the StringBuffer's reverse function: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceFirst-java.lang.String-java.lang.String-

以下是有关 replaceFirst String 方法和 StringBuffer 的反向函数的文档:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceFirst-java.lang.String-java 。 lang.String-

https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#reverse--

https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#reverse--

Here is how I implemented it to simply remove some html 'pre' tags from a code snippet that I wanted to interpret. Remember to reverse your search string as well, and then reverse everything back to normal afterwords.

这是我如何实现它以简单地从我想要解释的代码片段中删除一些 html 'pre' 标签。请记住也反转您的搜索字符串,然后将所有内容反转回正常的后记。

private String stripHtmlPreTagsFromCodeSnippet(String snippet) {
    String halfCleanSnippet = snippet.replaceFirst("<pre>", "");
    String reverseSnippet = new StringBuffer(halfCleanSnippet).reverse().toString();
    String reverseSearch = new StringBuffer("</pre>").reverse().toString();
    String reverseCleanSnippet = reverseSnippet.replaceFirst(reverseSearch, "");
    return new StringBuffer(reverseCleanSnippet).reverse().toString();
}