Java issue - regex

I want to remove a character )from the end of a line through a regular expression.

For example, if the string is Great Britain (Great Britain), then I want to replace the last character ).

Note:

1). The regular expression should remove only the last character ), it does not matter how many characters )are present in the string.

+3
source share
5 answers

Please do not use regex for this simple task.

// If the last ) might not be the last character of the String
String s = "Your String with) multiple).";
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(s.lastIndexOf(')'));
s = sb.toString(); // s = "Your String with) multiple."

// If the last ) will always be the last character of the String
s = "Your String with))";
if (s.endsWith(")")) 
    s = s.substring(0, s.length() - 1);
// s = "Your String with)"
+9
source

If only the end )at the end of the line should be removed, then this works:

str.replaceFirst("\\)$", "");

, : ) (, ), $, , ).

, , ) ( ), , .


), , .*:

str.replaceFirst("(.*)\\)", "$1");

.*, \1. - , \1 , , , ), , ( , right, \1 , ).


O(1) $. O(N), , . , , , O(1) . , .

O(N) - . ) lastIndexOf, O(N).

, Pattern replaceFirst. API:

str.replaceFirst(regex, repl)

,

Pattern.compile(regex).matcher(str).replaceFirst(repl)

" replaceFirst, , ."

, replaceAll , ! , replaceAll replaceFirst , !

needle$ , (.*)needle - , , . "".

replaceFirst - , : , ; , , , "Sense" "Mohican"!

: "spam" . , replace

str.replace("spam", "");

" ! replace ! - ! delete - !"

, ! - - ! - , - replace -ment!

, replaceFirst : -, !

, , , :

public static String removeLastCloseParenthesis(String str) {
   return str.replaceFirst("(.*)\\)", "$1");
}

. . , , , .

+3

( , )

String s = /* ... your string here ... */
String parenReplacement = "!!!" // whatever the replacement is
Pattern p = Pattern.compile("^(.*)\\)([^\\)]*)$");
Matcher m = p.matcher(s);
if (m.find())
{
   s = m.group(1)+parenReplacement+m.group(2);
}
+2

Why would you use regex? Just use String.charAt (...) and the substring (...)!

+1
source

You do not need regex for this. The class Stringhas a method lastIndexOf()that can be used to find the index of the last) in String. See here .

0
source

Source: https://habr.com/ru/post/1741303/


All Articles