Search code examples
javaregexstringreplacealphanumeric

Java remove all non alphanumeric character from beginning and end of string


I know how to replace ALL non alphanumeric chars in a string but how to do it from just beginning and end of the string?

I need this string:

"theString,"

to be:

theString

replace ALL non alphanumeric chars in a string:

s = s.replaceAll("[^a-zA-Z0-9\\s]", "");

Solution

  • Use ^ (matches at the beginning of the string) and $ (matches at the end) anchors:

    s = s.replaceAll("^[^a-zA-Z0-9\\s]+|[^a-zA-Z0-9\\s]+$", "");