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

Mike6679 picture Mike6679 · Jul 26, 2014 · Viewed 15.3k times · Source

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

falsetru picture falsetru · Jul 26, 2014

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