haughtonomous
haughtonomous

Reputation: 4850

Regex permits forbidden strings - can anyone advise?

I want to test that a string is an exact match for one of a number of patterns.

I think I can do this with

myRegex.IsMatch(testString) && myregex.Match.ToString()==testString 

but can this be done in the regex pattern itself?

I want to test that testString matches either DOC or EMAIL exactly, or HTML::sometexthere or CSV::sometexthere. It must not match DOC::sometexthere, for example - that should be a 'fail'

My current regex pattern is ^(DOC|EMAIL)|((CSV|HTML)::.+), but that allows forbidden strings such as DOC::sometexthere

TIA

Upvotes: 0

Views: 129

Answers (2)

woutervs
woutervs

Reputation: 1510

The following regex should do exactly what you ask: ((DOC|EMAIL)|((HTML|CSV)::.*))

Was tested on the following strings:

  • DOC - match
  • EMAIL - match
  • EMAIL::someTextHere - no match
  • DOC::someTextHere - no match
  • HTML::SomeTextHere - match
  • CSV::someTextHere - match

UPDATE Change it to this and it should sattisfy your needs completely.

((DOC|EMAIL)$|((HTML|CSV)::.+))

Added the $ so it wouldn' capture the DOC in DOC::sometext changed the * to + so it should atleast contain one character behind the ::

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89567

Your pattern is correct, but you must add a 'end of string' anchor $:

 ^((DOC|EMAIL)|((CSV|HTML)::.+))$

Note that I have enclosed the two possibilities inside parenthesis.

Upvotes: 0

Related Questions