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

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

java - A regex that doesn't match with this character sequence

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...