Reputation: 384
I've created the following regex:
(^[%a-zA-Z][\w\-.]+)( [\w\-.]+|[\w\-.]+)([%A-Za-z.]$)
strings that should be allowed e.g.
test (working)
test test (working)
%test (working)
test% (working)
%test% (working)
% (not working)
I tried the following to make % only work:
(%|(^[%a-zA-Z][\w\-.]+)( [\w\-.]+|[\w\-.]+)([%A-Za-z.]$))
the defined pattern works fine with https://www.debuggex.com, but fails in my application, where the model looks like:
[Display(Name = "Publisher")]
[RegularExpression(@"(%|(^[%a-zA-Z][\w\-.]+)( [\w\-.]+|[\w\-.]+)([%A-Za-z.]$))", ErrorMessage = "Invalid Expression!")]
public string SoftwarePublisher { get; set; }
any advice would be helpful. thanks in advance
Upvotes: 4
Views: 439
Reputation: 3059
This pattern should be bit better than yours give it a try as it works for me:
PATTERN
(^|%)((\w+\s?)+)([^\s]$|%)|%
INPUT
case 1: test
case 2: test
case 3: %test
case 4: test%
case 5: %test%
case 6: %
OUTPUT
case 1: matches
case 2: matches
case 3: matches
case 4: matches
case 5: matches
case 6: matches
Hope it will work for you or at least give you some hint. If you will test it on some website use all strings separately as I'm using ^
and $
.
Upvotes: 1
Reputation: 1835
The expression you are using will simply test negative for all string less then 4 characters. 2 for group 1, 1 (of 2) for group 2, and 1 for group 3.
You can check this to test with 'tes' which will fail, and '%%%%' which will pass (even if you take % out of you regex).
If you want help with the regex let us know what you are trying to achieve. In any case, writing down what you want your regex to do in human readable language first is advisable.
For instance:
Any string that:
starts with 3 letters
an optional '_'
etc.
Upvotes: 0