Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude certain characters using RegEx

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#
like image 419
gbn Avatar asked Jul 14 '09 20:07

gbn


People also ask

Can regex remove characters?

To replace or remove characters that don't match a regex, call the replace() method on the string passing it a regular expression that uses the caret ^ symbol, e.g. /[^a-z]+/ . The replace method will return new string where the not matching characters are replaced or removed. Copied!

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.

Can you use wildcard in regex?

In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters.


3 Answers

^[^\'\ ]*$
?
like image 88
Wojciech Bederski Avatar answered Oct 16 '22 09:10

Wojciech Bederski


Quite simple. Does not allow empty strings.

^[^' ]+$
like image 32
Daniel Brückner Avatar answered Oct 16 '22 10:10

Daniel Brückner


i think this

^\w*$

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

like image 2
Victor Avatar answered Oct 16 '22 09:10

Victor