2

So I'm not very familiar with Regex, seen some tutorials and how it works, but I still don't get it!

Anyways, here's the current string that I have: ^[a-zA-Z0-9]*$

I want it to be able to use the following characters: [ ] ( ) | (and to be able to use spaces)

Edit: For spaces, lets say the following string: [Something] Something, is it alright to have the Regex like: ^[][a-zA-Z0-9 ]*$?

1
  • Yup, that's perfect. The last thing (literally, there's nothing else that I'm aware of) you should know is that dashes belong at the end (or beginning) of the character class, because otherwise they'd specify ranges. Commented Sep 13, 2012 at 0:16

2 Answers 2

3

You need to escape the closing square bracket ] (only) in the character class:

^[[\]a-zA-Z0-9 ()|]*$

All other characters you need to use don't require escaping.


As an aside, the only characters you need to escape inside a character class are:

  • ] the closing bracket (obviously)
  • \ the backslash (obviously)
  • ^, but only if not in a negative class (one starting with ^)
  • -, but only if not the first or last character in the character class

All other characters lose their regex meanings when used in a character class. For example, this is a valid character class:

[^^.*()|[\]\\-]

which means "any character except any of ^.*()|[]\- "

Sign up to request clarification or add additional context in comments.

1 Comment

@acheong87 Lack of coffee maybe?
2

Include ] in the beginning of a character class, like so:

^[]a-zA-Z0-9]*$

The rest can be inserted unescaped:

^[][()|a-zA-Z0-9]*$

Except if you're not talking about character classes of course.

EDIT: The opening bracket can be interpreted as a bracket expression, so it may be safer to escape that one:

^[]\[()|a-zA-Z0-9]*$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.