views:

788

answers:

5

Try as I might, I can't get a RegEx to exclude space or single quotes.

  • The string "abc" is allowed
  • Not allowed: "a'bc", "'", "'abc", "'''", "abc''" etc
  • Spaces could replace the ' too in the above example
  • Trailing and leading spaces are assumed to be removed already
  • Empty strings are checked elsewhere
  • Target language is javascript

I'd use PATINDEX if I was in SQL.

Or NOT a positive match on either space or single quote, if I could negate...

I've tried (for single quote only)

  • \w*[^']\w*
  • ^\w*[^']\w*$
  • others I forget now

Please put me out of my misery so I can sleep tonight.

Edit:

  • Target string will not be surrounded by Quotes. I thought thy might add clarity
  • If "Target language is javascript" is wrong, then it's c#. I'd have to check where we do the validation exactly: client javascript or server c#
+3  A: 

^[^\'\ ]*$
?

wuub
I used ^[^' ]*$ ...I see where I was going wrong. Thanks
gbn
Yeah, I always escape to much...
wuub
A: 

Without reading the details, I don't see [^ '] in there anywhere (with a space and a single-quote).

le dorfier
Correct. I was initially testing for single quote only
gbn
..which was mentioned...
gbn
+4  A: 

Quite simple. Does not allow empty strings.

^[^' ]+$
Daniel Brückner
wuub answered first but thanks +1. This also works. Why + and not * though please?
gbn
+1 for the non escaped version. You're probably better regexper that I am :)
wuub
+ instead of * to disallow empty strings.
Daniel Brückner
A: 

i think this

^\w*$

should work as \w does not include single quote or space.

Victor
A: 

Looks like your question has been answered. If not, please provide more details about where the string is coming from.

If you are trying to restrict a field that is being entered by a user, you could check each key stroke rather than the entire string.

Kyle Jones
Yes, we are trying to restrict use data entry. No, we can't do it per key stroke. Our RegEx is a database field to be applied on validation.
gbn