3

I have a very simple regex that does not appear to be working as it should. The desired outcome of my regex is that I use it alongside replaceAll to replace any character that is not a-z, A-Z, or 0-9 with nothing(""). I realize there are many questions about the same thing but I am new to regex and the ones I see in those questions are MUCH too complicated to help me debug my own. I even tried using regexr.com to help me to no avail.

Here is my regex:

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

I have tried many different things including variants of ^[^a-zA-Z0-9]+$ and ^[^a-zA-Z0-9]* but none of them work properly. They all seem to leave trailing punctuation on words which it should not be doing. Any suggestions are greatly appreciated. Thank you.

7
  • 1
    s = s.replaceAll("[^a-zA-Z0-9]", ""); Commented Nov 20, 2019 at 22:17
  • @JBNizet That works perfectly! Thank you so much. If you'd be so kind as to put it in an answer, I will mark it as correct so you can have the credit. Commented Nov 20, 2019 at 22:28
  • Your question is closed as duplicate. I can't answer it anymore. Read the duplicate for a real answer with an actual explanation. There is no reason for your regex to contain ^ at the beginning or $ at the end. All you want is to replace any substring that matches [^a-zA-Z0-9], i.e. which is not a letter nor a digit, to be replaced by nothing. Commented Nov 20, 2019 at 22:29
  • @JBNizet Oh okay. I figured it would. Was it really due to the ^ and $ like the duplicate statement says or was it because I wasn't doing s = ? Commented Nov 20, 2019 at 22:30
  • 1
    It was both (I thought you were correctly reassigning the value, since you told it leaf trailing punctuation. replaceAll returns a new string, without altering the original one. Commented Nov 20, 2019 at 22:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.