Reputation: 450
I want to validate list of tags - strings separated with space. Examples:
"blue white green123 #$#! ()!!!123 q_w_e_r_t_y"
The only requirement is that they cannot start with an underscore '_'. What is an appropriate regex expression to match those tags?
I wrote some test case to verify the correctness of the pattern:
public void RegexTest()
{
//arrange
const string pattern = @"^PATTERN$";
var regex = new Regex(pattern);
var positive = new[] { "AAA", "A_", "AAA AAA", "AAA_AAAA", "AAA_AA AAA_aaa AA___ AAA", "A____", "333A%#$%#@%$__=-21-2-AA213", "+=-_0987654321`!@#$%^&*() qwertyu:/.," };
var negative = new[] { "_AAAA", "A _AA ", "AA _AA", "A B _C", "_ " };
//act
var positiveMatches = positive.Select(x => regex.IsMatch(x)).ToArray();
var negativeMatches = negative.Select(x => regex.IsMatch(x)).ToArray();
//assert
CollectionAssert.AreEqual(positiveMatches.Select(x => true).ToArray(), positiveMatches);
CollectionAssert.AreEqual(new bool[negativeMatches.Length], negativeMatches);
}
Upvotes: 0
Views: 196
Reputation: 67968
(?!^_)(?!.*?\s_\w)^.*$
Try this.See demo.
http://regex101.com/r/iO1uK1/5
Upvotes: 1
Reputation: 174706
Just use a negative lookahead to check for undescores preceeded by not of space or starting anchor.
^(?:(?!\s_|^_).)*$
Upvotes: 2