aligator
aligator

Reputation: 450

Regex for space separated strings that cannot start with underscore

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

Answers (3)

vks
vks

Reputation: 67968

(?!^_)(?!.*?\s_\w)^.*$

Try this.See demo.

http://regex101.com/r/iO1uK1/5

Upvotes: 1

anubhava
anubhava

Reputation: 785176

This regex should work:

^(?!(.*\s+)?_\w*\b).+$

RegEx Demo

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Just use a negative lookahead to check for undescores preceeded by not of space or starting anchor.

^(?:(?!\s_|^_).)*$

DEMO

Upvotes: 2

Related Questions