3

I need a Javascript and .NET regex that checks a string and lets me know if the string only containers one character other than a space.

I want to prevent users from entering something like "wwwwwwwwww wwwwwwwwwww wwwwwwwwwww" but allow them to enter things like "cccccccc ddddddddd".

I'm so bad at regex, so I'm sorry for not coming with code.

1
  • 1
    A little confused by your question...will you allow up to one space character? Would you allow no space characters? Commented Jun 18, 2011 at 16:02

1 Answer 1

2
 string [] inputs = {" sdfasf asdf ", " wwwwww wwwwwww ", " aaaaa bbbb ccccccc"};
 foreach (string input in inputs)
 {
    var match = Regex.Match (input, @"^\s*(\w)(?:\1|\s)*$");
    Console.WriteLine (input + "\t" + match.Success);
 }

The regex doesn't use any special characters and I believe it will work in javascript as well. In C#, it prints:

sdfasf asdf    False
wwwwww wwwwwww         True
aaaaa bbbb ccccccc     False
Sign up to request clarification or add additional context in comments.

8 Comments

Your regex will match "wwwwwwwwww wwwwwwwwwww wwwwwwwwwww" which is what the OP doesn't want.
This is right, though the OP may want to use "\S" instead of "\w".
@Darin I think he wants to match that string so that it can be disallowed. In other words, he wants the regex to detect the illegal input.
@Pointy, but then this contradicts with "aaaaa bbbb ccccccc" for which this regex returns false.
I think this solution provides what the OP wants, though he may need to use the whether the regex fails rather than succeeds.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.