Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here is my Regex, I am trying to search all special characters so that I can escape them.

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

My problem here is, I don't want to escape some sepcial characters only when the come in a sequence

like this (.*)

So, Lets consider an example.

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

After escaping according to current regex what i get is,

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

But is don't want to escape this part (.*) want to keep it as it is.

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

Can anyone suggest regex that doesn't escape that part of the string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
806 views
Welcome To Ask or Share your Answers For Others

1 Answer

See @nhahtdh for how to do this with a regex.

As an alternative, Here is a solution which does not use a regex, using Guava's CharMatcher instead:

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...