I need to match my string if it starts with any number of whitespaces or ends with any number of spaces:
my current regex includes also the spaces inbetween:
(^|\s+)|(\s+|$)
how can I fix it to reach my goal?
update:
this doesn't work, because it matches the spaces. I want to select the whole string or line rather, if it starts with or ends with whitespace(s).
I need to match my string if it starts with any number of whitespaces or ends with any number of spaces:
my current regex includes also the spaces inbetween:
(^|\s+)|(\s+|$)
how can I fix it to reach my goal?
update:
this doesn't work, because it matches the spaces. I want to select the whole string or line rather, if it starts with or ends with whitespace(s).
Share Improve this question edited Aug 10, 2017 at 18:49 cplus asked Aug 10, 2017 at 18:29 cpluscplus 1,1154 gold badges25 silver badges57 bronze badges 1-
/^(\s.*|.*\s)$/
should work for you. – anubhava Commented Aug 10, 2017 at 18:52
5 Answers
Reset to default 9modify it to the following
(^\s+)|(\s+$)
Based on modified OP, Use this Pattern ^\s*(.*?)\s*$
Demo look at capturing group #1
^ # Start of string/line
\s # <whitespace character>
* # (zero or more)(greedy)
( # Capturing Group (1)
. # Any character except line break
*? # (zero or more)(lazy)
) # End of Capturing Group (1)
\s # <whitespace character>
* # (zero or more)(greedy)
$ # End of string/line
You can use this: https://regex101./r/gTQS5g/1
^\s|\s$
Or with .trim()
you could do without the regex:
myStr !== myStr.trim()
No need to create groups. You can create one alternation.
^\s+|\s+$
Live demo
modify it to the regex below
(^\s+.*)|(.*\s+$)
you can check the demo
this could help you , see demo here
^\s+.*|.*\s+$