A regular expression that does not match this character sequence

Here is my Regex, I am trying to find all the special characters so that I can avoid them.

(\(|\)|\[|\]|\{|\}|\?|\+|\\|\.|\$|\^|\*|\||\!|\&|\-|\@|\#|\%|\_|\"|\:|\<|\>|\/|\;|\'|\`|\~)

My problem is that I do not want to avoid some characters only when they enter the sequence

like this (.*)

So, consider an example.

Sting message = "Hi, Mr.Xyz! Your account number is :- (1234567890) , (,*) &$@%#*(....))(((";

After escaping according to the current regular expression, what I get is

Hi, Mr\.Xyz\! Your account number is \:\- \(1234567890\) , \(,\*\) \&\$\@\%\#\*\(\.\.\.\.\)\)\(\(\(

But I do not want to avoid this part (.*)in order to keep it as it is.

My regex above is only used for searching, so I just don't want to match this part (.*), and my problem will be solved.

Can anyone suggest a regex that does not escape this part of the string?

-4
2

. .

Java String replaceAll:

String input = "Hi, Mr.Xyz! Your account number is :- (1234567890) , (.*) &$@%#*(....))(((";
String output = input.replaceAll("\\G((?:[^()\\[\\]{}?+\\\\.$^*|!&@#%_\":<>/;'`~-]|\\Q(.*)\\E)*+)([()\\[\\]{}?+\\\\.$^*|!&@#%_\":<>/;'`~-])", "$1\\\\$2");

:

"Hi, Mr\.Xyz\! Your account number is \:\- \(1234567890\) , (.*) \&\$\@\%\#\*\(\.\.\.\.\)\)\(\(\("

:

String input = "(.*) sdfHi test message <> >>>>><<<<f<f<,,,,<> <>(.*) sdf (.*)  sdf (.*)";

:

"(.*) sdfHi test message \<\> \>\>\>\>\>\<\<\<\<f\<f\<,,,,\<\> \<\>(.*) sdf (.*)  sdf (.*)"

:

\G((?:[^()\[\]{}?+\\.$^*|!&@#%_":<>/;'`~-]|\Q(.*)\E)*+)([()\[\]{}?+\\.$^*|!&@#%_":<>/;'`~-])

, \ , , " . .

:

$1\\$2

$ , $2, \, \ $. , \, \.

, . , , . , , , ( , , , ).

, : [0 or more (non-special character or special pattern not to be replace)][special character], [0 or more (non-special character or special pattern not to be replace)].

replaceAll \G , , , , . \G , , .

  • \G:

  • ((?:[^()\[\]{}?+\\.$^*|!&@#%_":<>/;'`~-]|\Q(.\*)\E)*+): 0 , , . , + *. , , .

    • [^()\[\]{}?+\\.$^*|!&@#%_":<>/;'`~-]: .

    • \Q(.*)\E: (.*) , \Q \E.

  • ([()\[\]{}?+\\.$^*|!&@#%_":<>/;'`~-]): .

1 ( ). , , , .

+2

@nhahtdh , .

, , , Guava CharMatcher:

private static final CharMatcher SPECIAL
    = CharMatcher.anyOf("allspecialcharshere");
private static final String NO_ESCAPE = "(.*)";

public String doEncode(String input)
{
    StringBuilder sb = new StringBuilder(input.length());

    String tmp = input;

    while (!tmp.isEmpty()) {
        if (tmp.startsWith(NO_ESCAPE)) {
            sb.append(NO_ESCAPE);
            tmp = tmp.substring(NO_ESCAPE.length());
            continue;
        }
        char c = tmp.charAt(0);
        if (SPECIAL.matches(c))
            sb.append('\\');
        sb.append(c);
        tmp = tmp.substring(1);
    }

    return sb.toString();
}
+3

All Articles