How to remove all special characters except for underscore between two words in java?

Viewed 639

I want to remove all special characters from the string object below with some characters except for _(underscore) between two words in java ?

my sample data would be

a = *OIL~
b = OIL_GAS_
c = *OIL_GAS$
b = OIL_GAS

This is the output I'm expecting:

OIL
OIL_GAS
OIL_GAS
OIL_GAS

I already have this String str1= s.replaceAll("(\\W)*", ""); And I could remove all special characters. If any one could help me update my code How to remove all special characters except for underscore between two words

Any help would be great thanks.

3 Answers

The RegEx pattern, [^\p{Alnum}_]|^_|_$ meets your requirement.

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream.of(
                    "OIL~", 
                    "_OIL_GAS",
                    "OIL_GAS_", 
                    "_OIL_GAS_",
                    "*OIL_GAS$", 
                    "OIL_GAS"
                ).forEach(s -> System.out.println(s.replaceAll("[^\\p{Alnum}_]|^_|_$", "")));
    }
}

Output:

OIL
OIL_GAS
OIL_GAS
OIL_GAS
OIL_GAS
OIL_GAS

Explanation of the regex at regex101:

enter image description here

Note: As you must have already understood from the documentation, \p{Alnum} is same as A-Za-z0-9.

Maybe s.replaceAll("[^A-Z0-9_]", "");

Basically anything that is not a letter, number or underscore. If you don't want to include numbers try [^A-Z_]

Update:

(?!_|^w)[^a-zA-Z]*|^_+|[^a-zA-Z]*(?=_|$)

https://regex101.com/r/SZ8zGb/1

Your code String str1= s.replaceAll("(\W)*", ""); is already ok for your use case. this will remove special characters except underscore

Related