Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 285
cplus Avatar asked Aug 10 '17 18:08

cplus


People also ask

What is regex for whitespace?

The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].

How do you stop a space in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs).

Does \w include spaces regex?

\W means "non-word characters", the inverse of \w , so it will match spaces as well.

How do you find a space in a string in regex?

Spaces can be found simply by putting a space character in your regex. Whitespace can be found with \s . If you want to find whitespace between words, use the \b word boundary marker.


3 Answers

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
like image 104
alpha bravo Avatar answered Oct 29 '22 00:10

alpha bravo


You can use this: https://regex101.com/r/gTQS5g/1

^\s|\s$

Or with .trim() you could do without the regex:

myStr !== myStr.trim()
like image 29
spanky Avatar answered Oct 28 '22 22:10

spanky


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

^\s+|\s+$

Live demo

like image 28
linden2015 Avatar answered Oct 29 '22 00:10

linden2015