RegEx - remove leading and trailing spaces when content matches

I want to try and build a RegEx statement that will remove any pre-differentiated or trailing spaces from the string (but don't leave those contained in the string intact), as well as those that match the selected format. For example, a string must be no more than 20 characters, can contain any characters from a-zA-Z0-9, as well as underscores and hyphens. But most importantly, it should trim or ignore any whitespace found at the beginning or end of the line, like so:

Correct: "Have a nice day"

Wrong: "Have a nice day"

I have tried many different ways to do this, but unfortunately so far I have not been able to find a formula that does exactly what I want. Can anyone help me with a suitable RegEx? (this is RegEx in its simplest form, not platform specific).

+3


source to share


5 answers


Find this pattern:

^\s*(.*?)\s*$

      



Replace this:

\1

      

+4


source


It seems from your example that the space is also allowed in the middle of the line, so try this

^((([a-zA-Z0-9\-_][a-zA-Z0-9\-_ ]{0,18}?[a-zA-Z0-9\-_]))|([a-zA-Z0-9\-_]))$

      



Anything that matches is true.

A section or

in a template is used to support a single character sentence.

0


source


This should suit your needs:

^\S[\w\s-]{0,18}\S$

      

18

are maxlength - 2

strings, because of the two \S

, which will match any non-whitespace char. For example, in this case, the strings will not match if their length is higher than 20

. Moreover, strings will not match if their length is less than 2

characters, due to the same above restriction.

0


source


use this regex ^\S((.{0,18}\S)|)$

^

start of line

\S

nonspatial symbol

(.{0,18}\S)?

any character and non-space character at the end (0-19 characters)

|

or

$

end of line

0


source


Here is an example using sed

echo "  Have a nice day  "|sed -E "s/^ *([^ ]+.*[^ ]+) +$/\\1/"

      

0


source







All Articles