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.

1Poseidon3
  • 123
  • 1
  • 11
  • 1
    `s = s.replaceAll("[^a-zA-Z0-9]", "");` – JB Nizet Nov 20 '19 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. – 1Poseidon3 Nov 20 '19 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. – JB Nizet Nov 20 '19 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 = ` ? – 1Poseidon3 Nov 20 '19 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. – JB Nizet Nov 20 '19 at 22:32
  • @JBNizet Okay thank you very much for clearing that up for me. You are a saint. – 1Poseidon3 Nov 20 '19 at 22:34
  • @1Poseidon3 Both duplicates are of importance. – Wiktor Stribiżew Nov 20 '19 at 23:59

0 Answers0