如何从字符串中删除所有结束插入符?

时间:2021-05-07 21:44:54

How do I remove all the ending caret characters from end of a string?

如何从字符串末尾删除所有结束插入符?

For example: I have a string with value "t^e^st ^^^^^^^^" My output should be "t^e^st". How can I do this using Java regex?

例如:我有一个值为“t ^ e ^ st ^^^^^^^^”的字符串我的输出应为“t ^ e ^ st”。如何使用Java正则表达式执行此操作?

2 个解决方案

#1


2  

"t^e^st ^^^^^^^^".replaceAll("\\^*$", '')

The caret also needs to be escaped. \\s* takes care of any trailing whitespace also.

插入符也需要逃脱。 \\ s *也会处理任何尾随空格。

#2


0  

Try anchoring a repeated ^ to the end of the String, like this:

尝试将重复的^锚定到String的末尾,如下所示:

"t^e^st ^^^^^^^^".replaceAll("(.*)\\^*$", "$1").trim();

“t ^ e ^ st ^^^^^^^^”。replaceAll(“(。*)\\ ^ * $”,“$ 1”)。trim();

This looks for and captures any characters ((.*)) that are followed by 0 or more carats (\\^*) at the end of the string ($). Then it replaces all of that with the first capture group ($1) and trims the string to remove any leading/trailing spaces. The result should be just "t^e^st".

这会查找并捕获字符串末尾(0)后面跟着0或更多克拉(\\ ^ *)的任何字符((。*))。然后它用第一个捕获组($ 1)替换所有这些并修剪字符串以删除任何前导/尾随空格。结果应该只是“t ^ e ^ st”。

#1


2  

"t^e^st ^^^^^^^^".replaceAll("\\^*$", '')

The caret also needs to be escaped. \\s* takes care of any trailing whitespace also.

插入符也需要逃脱。 \\ s *也会处理任何尾随空格。

#2


0  

Try anchoring a repeated ^ to the end of the String, like this:

尝试将重复的^锚定到String的末尾,如下所示:

"t^e^st ^^^^^^^^".replaceAll("(.*)\\^*$", "$1").trim();

“t ^ e ^ st ^^^^^^^^”。replaceAll(“(。*)\\ ^ * $”,“$ 1”)。trim();

This looks for and captures any characters ((.*)) that are followed by 0 or more carats (\\^*) at the end of the string ($). Then it replaces all of that with the first capture group ($1) and trims the string to remove any leading/trailing spaces. The result should be just "t^e^st".

这会查找并捕获字符串末尾(0)后面跟着0或更多克拉(\\ ^ *)的任何字符((。*))。然后它用第一个捕获组($ 1)替换所有这些并修剪字符串以删除任何前导/尾随空格。结果应该只是“t ^ e ^ st”。