I am looking for a regular expression for matching that contains no white space in between text but it may or may not have white space at start or end of text.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You want something like this: (see it in action on rubular.com):
Explanation:
^is the beginning of the string anchor$is the end of the string anchor\sis the character class for whitespace\Sis the negation of\s(note the upper and lower case difference)*is “zero-or-more” repetition+is “one-or-more” repetitionReferences
Can the “text” part be empty?
The above pattern does NOT match, say, an empty string. The original specification isn’t very clear if this is the intended behavior, but if an empty “text” is allowed, then simply use
\S*instead, i.e. match zero-or-more (instead of one-or-more) repetition of\S.Thus, this pattern (same as above except
*is used instead of+)will match:
What counts as “text” characters?
The above patterns use
\Sto define the “text” characters, i.e. anything but whitespace. This includes things like punctuations and symbols, i.e. the string" #@^$^* "matches both patterns. It’s not clear if this is the desired behavior, i.e. it’s possible that" ==== AWESOMENESS ==== "is a desired matchThe pattern still works even for this case, we simply need to be more specific with our character class definitions.
For example, this pattern:
Will match (as seen on rubular.com):
But not:
Note that the
^metacharacter, when used as the first character in a character class definition, no longer means the beginning of the string anchor, but rather a negation of the character class definition.Note also the use of the
/imodifier in the pattern: this enables case insensitive matching. The actual syntax may vary between languages/flavors.References
java.util.regex.Pattern.CASE_INSENSITIVE— embedded flag is(?i)