I have this string 'Enterprise - SELA'; And I want to convert it to 'Enterprise_SELA'; I can do this with the regex: \W+


 original.replace('\W+', '_') 

throws the

Illegal character sequence \W'

error and

original.replace('\\W+', '_') 

doesn't carry out the replacement. Nor does original.replace('\\W+', '_')


You need to use String.replaceAll, not String.replace. String.replace only looks for a literal string.

String original = 'Enterprise - SELA';
String replaced = original.replaceAll('\\W+', '_');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.