Reputation: 1115
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?
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).
Upvotes: 5
Views: 6795
Reputation: 7948
modify 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
Upvotes: 9
Reputation: 10458
modify it to the regex below
(^\s+.*)|(.*\s+$)
you can check the demo
Upvotes: 1
Reputation: 2870
You can use this: https://regex101.com/r/gTQS5g/1
^\s|\s$
Or with .trim()
you could do without the regex:
myStr !== myStr.trim()
Upvotes: 3
Reputation: 887
No need to create groups. You can create one alternation.
^\s+|\s+$
Upvotes: 1