2

I'm trying to use the String.replaceAll() method with regex to only keep letter characters and ['-_]. I'm trying to do this by replacing every character that is neither a letter nor one of the characters above by an empty string.

So far I have tried something like this (in different variations) which correctly keeps letters but replaces the special characters I want to keep:

current = current.replaceAll("(?=\\P{L})(?=[^\\'-_])", "");
1
  • Note that between square brackets, '-_ means “any character between ' and _”, which is probably not what you want. You should either escape the - or place it last before the ]. Commented Dec 17, 2015 at 15:30

4 Answers 4

1

Make it simplier :

current  = current.replaceAll("[^a-zA-Z'_-]", "");

Explanation : Match any char not in a to z, A to Z, ', _, - and replaceAll() method will replace any matched char with nothing.

Tested input : "a_zE'R-z4r@m" Output : a_zE'R-zrm

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need lookahead, just use negated regex:

current = current.replaceAll("[^\\p{L}'_-]+", "");

[^\\p{L}'_-] will match anything that is not a letter (unicode) or single quote or underscore or hyphen.

Comments

0

Your regex is too complicated. Just specify the characters you want to keep, and use ^ to negate, so [^a-z'_-] means "anything but these".

public class Replacer {
    public static void main(String[] args) {
        System.out.println("with 1234 &*()) -/.,>>?chars".replaceAll("[^\\w'_-]", ""));
    }
}

Comments

0

You can try this:

String str = "Se@rbi323a`and_Eur$ope@-t42he-[A%merica]";
str = str.replaceAll("[\\d+\\p{Punct}&&[^-'_\\[\\]]]+", "");
System.out.println("str = " + str);

And it is the result:

str = Serbia'and_Europe-the-[America]

Comments

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.