Mike6679 Mike6679 - 1 month ago 6
Java Question

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]", "");

Answer

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]+$", "");