cplus
cplus

Reputation: 1115

regex match if starts or ends with whitespaces

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).

Upvotes: 5

Views: 6795

Answers (5)

Ali Faris
Ali Faris

Reputation: 18592

this could help you , see demo here

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

Upvotes: 0

alpha bravo
alpha bravo

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

marvel308
marvel308

Reputation: 10458

modify it to the regex below

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

you can check the demo

Upvotes: 1

spanky
spanky

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

linden2015
linden2015

Reputation: 887

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

^\s+|\s+$

Live demo

Upvotes: 1

Related Questions