Regex to match a string that does not start and / or end with spaces, but allows trailing spaces

I need the regex to not match lines that start and / or end with space (s) but match between spaces. I am not a regex expert.

I can use 2 regular expressions if needed.

Note. Use .

to show space in examples.

matches false for

 .text.
 ..text
 text..
 ..te.xt..

      

matches true for

 text
 te..xt

      

I came up with this. It only matches the initial spaces.

^(?!\s+).*$

      

+3


source to share


3 answers


This template should do the trick:

^\S+.*?\S+$

      



And usage:

Regex.IsMatch(input, @"^\S+.*?\S+$"))

      

+1


source


You can use a character class \S

with bindings ^

and $

.

^\S(.*\S)?$

      



Optional grouping is .*\S

required to match a single nonspatial symbol.

+6


source


It might be easier to combine what you don't want and then reverse it:

!Regex.IsMatch(input, @"(^\s)|(\s$)")

      

+1


source







All Articles