Regular expression if it starts or ends with spaces

I need to match my line if it starts with any number of spaces or ends with any number of spaces:

my current regular expression also includes spaces between them:

(^|\s+)|(\s+|$)

How can I fix this to achieve my goal?

update:

this does not work because it matches spaces. I want to select a whole line or a line if it starts or ends with spaces.

+4
source share
5 answers

change it to the following

(^\s+)|(\s+$)

Based on the changed OP, use this ^\s*(.*?)\s*$ Demo template to see 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
+2
source

: https://regex101.com/r/gTQS5g/1

^\s|\s$

.trim() :

myStr !== myStr.trim()
+3

change it to regex below

(^\s+.*)|(.*\s+$)

you can check the demo

+1
source

No need to create groups. You can create one rotation.

^\s+|\s+$

Live demo

+1
source

this can help you see the demo here

^\s+.*|.*\s+$
0
source

Source: https://habr.com/ru/post/1683464/


All Articles