2

I have two regexes.

One is for no space at the beginning and end but there can be a space in between words:

^[^\s]+(\s+[^\s]+)*$

And the second one is for allowing some special characters:

 ([^\\~!@#$%^&*()+=?<>|/""]*)

Now, I want to combine both regex into a single regex.

I have tried with | sign suggested in another post but that is not working for me.

I am using ASP.NET MVC data annotations.

Valid are:
"A"
"A."
"A,"
"A'S"
Invalid are:
 " A "
 " A"
 " B"
 "A@"
 "A!"
2
  • 2
    Can you post valid inputs Commented Jul 16, 2015 at 7:12
  • It sounds like Trim does exactly what your first is doing... Can you please explain what "not working" entails too? Commented Jul 16, 2015 at 7:13

1 Answer 1

1

You can use one regex to restrict the other within a lookahead:

^(?=([^\\~!@#$%^&*()+=?<>|/""]*)$)[^\s]+(\s+[^\s]+)*$

See demo (note I added \r? for demo purpose in multiline mode, and had to replace \s with literal space, but I guess that will not be necessary).

Sign up to request clarification or add additional context in comments.

1 Comment

Does it work for you? If not, or you have doubts, please provide the exact requirements, and if possible, the code where you are using the regex patterns.

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.