tags:

views:

106

answers:

4

Here are my requirements:

  • 1-80 characters
  • These characters are allowed:
    • alphanumeric
    • spaces
    • _ ( ) [ ] ! # , . & * + : ' / -

The regex I have below works, but in particular I'm not sure how to reuse the character class [\w\(\)\.\-\[\]!#,&*+:'\/]

[\w\(\)\.\-\[\]!#,&*+:'\/][\w\s\(\)\.\-\[\]!#,&*+:'\/]{0,79}

Update:

Thanks for all your answers, this one did the trick

^(?!\s)[\w\s().\-!#&]{1,80}$
+4  A: 

Does it really need to be 100% regex? Couldn't you just do

[\w\s\(\)\.\-\[\]!#,&*+:'\/]{1,80}

and separately verify that the first character isn't whitespace?

developmentalinsanity
+1 for thinking laterally.
Programming Hero
+3  A: 

Inside a character class, only ] and \ need escapes. Even - doesn't need an escape if it's the first character of the class!

Here's the simplest regex I could reduce it to:

[- \w().[\]!#,&*+:'/]{1,80}
Andomar
Make sure you don't use the ignore white space flag with this.
Geoff
Also this will only match spaces (\0x20) and not any other white space characters. This may be exactly what you want, but watch out for Unicode spaces and such like.
Geoff
`-` also needs no escaping as the last character in the class: `[a-z-]`, or directly positioned after a range: `[a-c-d]` (matches `a-c`, `-` or `d`). And even `]` needs no escaping if it's the first character in the class: `[]a]` matches an `]` or `a`.
Bart Kiers
+2  A: 

You could use a negative look ahead to check the first character is not white space. Then there is no need to reuse a character class.

(?!\s)[\w\s\(\)\.\-\[\]!#,&*+:'\/]{1,80}
Reuben Peeris
+3  A: 

If the first character can't be white space try this: (?!\s)[-\w\s().[\]\\!#,&*+:'/]{1,80}. You may want to "bracket" with ^ in the beginning and $ at the end ^(?!\s)[-\w\s().[\]\\!#,&*+:'/]{1,80}$, to have the regex match the whole string.

Geoff
You can drop the brackets around `\s`. Other than that, I like this one best.
Tim Pietzcker
Oh, and you might want to anchor it with `^` and `$` - but that's for the OP to decide.
Tim Pietzcker
Doesn't work with "test test test"
Chris Ballance
"test test test" fails because space is not in the class. I made that mistake in my first version, like the \\ which is also still here but shouldn't be.
Andomar
Thanks @Andomar that is why you got the up vote :-)
Geoff
+1 for making it better based on feedback
Chris Ballance