GLP
GLP

Reputation: 3675

How to write a regex for any text except quotes or multiple hyphens?

Can anybody tell me how to write a regular expression for "no quotes (single or double) allowed and only single hyphens allowed"? For example, "good", 'good', good--looking are not allowed (but good-looking is).

I need put this regex like following:

<asp:RegularExpressionValidator ID="revProductName" runat="server" 
     ErrorMessage="Can not have &quot; or '." Font-Size="Smaller" 
     ControlToValidate="txtProductName" 
     ValidationExpression="^[^'|\"]*$"></asp:RegularExpressionValidator>

The one I have is for double and single quotes. Now I need add multiple hyphens in there. I put like this "^[^'|\"|--]*$", but it is not working.

Upvotes: 1

Views: 572

Answers (2)

ovgolovin
ovgolovin

Reputation: 13410

So, the regexp has to fail when ther is ', or ", or --. So, the regexp should try this in every position, and if it's found, then fail:

^(?:(?!['"]|--).)*$

The idea is to consume all the line with ., but to check before using . each time that it not ', or ", or the beginning of --.

Also, I like the other answer very much. It uses a bit different approach. It consumes only non-'" symbols ([^'"]), and if it consumes -, it check if it's not followed by another -.

Also, there could be one more approach of searching for ', or ", or -- in the string, and then failing the regex if they are found. I could be achieved by using regex conditional expression. But this flavor of regex engine doesn't seem to support such kind of conditions.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

^(?:-(?!-)|[^'"-]++)*$

should do.

^          # Start of string
(?:        # Either match...
 -(?!-)    # a hyphen, unless followed by another hyphen
|          # or
 [^'"-]++  # one or more characters except quotes/hyphen (possessive match)
)*         # any number of times
$          # End of string

Upvotes: 2

Related Questions