0

I am trying to create a #replaceAll regex to file out certain characters.

I tried the following

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

but it gave me this error

INFO Caused by: java.util.regex.PatternSyntaxException: Unclosed character class near index 36
07.09 00:07:24 [Server] INFO [^\w~!@#$%^&*()-=_+`[]{}\|:;'"<>,./\]
07.09 00:07:24 [Server] INFO ^

I've tried searching online but don't know exactly what I'm doing wrong.

6
  • You need to escape -, [ and ] inside your character class Commented Sep 7, 2019 at 4:38
  • @Nick Do I escape with one \ or two \\ Commented Sep 7, 2019 at 4:41
  • Just single \ should be enough. Commented Sep 7, 2019 at 4:42
  • Not 100% certain for java but I think it's two. Commented Sep 7, 2019 at 4:43
  • @Nick It's telling me 'Invalid escape sequence' Commented Sep 7, 2019 at 4:43

2 Answers 2

1

For your regex expression,you have add \\ before the last ] and do not escape for the first [,and also you need to escape -,after changing it to

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

it works fine in my side

msg = msg.replaceAll("[^\\w~!@#$%^&*()\\-=_+`\\[\\]{}\\|:;'\\\"<>,./]", "");
Sign up to request clarification or add additional context in comments.

5 Comments

This worked but for some reason it's not replacing '\'
@Dan for '\' you need to escape itself
Isn't that way '\\\' does?
@Dan you need to use '\\\\' four backslash instead
BTW it is not the "before the last ]" - the last one should not be escaped since closing the [] pattern (example/code is correct (in that regard))
1

My guess is that maybe this expression might be desired or close to one:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

    public static void main(String[] args){


        final String regex = "[^\\w~!@#$%^&*()=_+`\\[\\]{}|:;'\"<>,.\\\/-]";
        final String string = "ábécédééefg";
        final String subst = "";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        final String result = matcher.replaceAll(subst);

        System.out.println(result);

    }
}

Output

bcdefg

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


1 Comment

just a little note: regex101 does not have the Java flavor, there might be some minor differences

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.