-2

I have a regex currently that allows letters, numbers, underscore and hyphen. Also allows string to be only between 1 and 255 characters long. I need to add to this regex to allow colon and parenthesis. Please assist. I tried a lot of variations and am at the loss.Just adding : and () to the list is not doing the trick. So if someone checks against this regex, it should allow string like ABCabc123():_-

 @"^[a-zA-Z0-9_-]{1,255}$"
coder
  • 19
  • 5
  • Should it allow strings like ABCabc)( with parenthesis unmatched? – Dour High Arch Sep 18 '18 at 17:19
  • yes. in any order...doesn't even have to be together.. can be ABCac12):_( – coder Sep 18 '18 at 17:20
  • 2
    `^[:\(\)a-zA-Z0-9_-]{1,255}$` – Dan Wilson Sep 18 '18 at 17:20
  • https://www.regular-expressions.info/characters.html#special has more information about escaping characters that have special meanings in regular expressions. – asherber Sep 18 '18 at 17:21
  • Try this ^[a-zA-Z0-9_:()-]{1,255}$ – John Sep 18 '18 at 17:22
  • Please show the regular expression that isn't working and the code you're using to test it that shows it not working. – Bill the Lizard Sep 18 '18 at 17:24
  • wow.. interesting. John, your solution works (I think) still testing. I was trying to put colon and parenthesis after _- that didn't work but between seems to do the trick – coder Sep 18 '18 at 17:24
  • 1
    `-` has a very specific meaning in a character class. If you're not careful with what goes before and after it, it will be interpreted differently... post your actual regex and actual errors. – Jeff Mercado Sep 18 '18 at 17:25
  • I used John's Regex in comments. It is working like I need it. Thank you everyone. I don't know how I can mark his answer correct. – coder Sep 18 '18 at 17:27

1 Answers1

0

Just escape parentheses like \( and \), anything else should be fine:

^[a-zA-Z0-9-_\(\):]{1,255}$
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171