I need a regular expression that makes sure a string does not start with or end with a space. I don't care if it has a space in the "middle" just not at the beginning or the end.
I have a regular expression that almost works:
^\S.*\S$
Here are some example results:
"HELLO" (Match)
"HEL LO" (Match)
" HELLO" (No Match)
"HELLO " (No Match)
"H" (No Match)
As you can see, the issue I am having is that when the string is only 1 character long ("H" in the example above) it doesn't return a match.
How do I modify my regular expression to handle the case where the string length is 1?
Thank you
NOTE - I am saving this data to an Xml file so I need a pattern to match the same thing in Xml schema. I am not sure if it's the same as whatever Regex in C# uses or not.
If anyone could provide me with the pattern to use in my schema that would be greatly appreciated!
You could do this:
It will match either a single non space character, followed by an optional zero-or-more characters followed by a single non space character.
Update
Given that you said this was for XML schema validation I tested it with this schema:
Against this sample document
So it appears that if you simply remove the start / end brackets. It works.
You use lookaround assertions, because they're zero-width:
It might be better to use negative assertions and positive character classes, though: