JeffreyC
JeffreyC

Reputation: 640

Regex help needed. with pattern matching

I'm new to Regex. The question asks me, Can you think of a regular expression to find spaces at the start and end of a string? Try it yourself before checking the spoiler below:

The solution is this: (?:^\s+)|(?:\s+$)

How does this Regex work?

Can you walk me through each step? What does this line of Regex do? Please help me out. Thanks.

Upvotes: 0

Views: 154

Answers (5)

Superman2013
Superman2013

Reputation: 41

For Regex pattern

          ^\s+ 

will find leading whitespaces

and the pattern \s+$ will find trailing whitespace.

You can read more about fun with regular expressions via this link:

Upvotes: 0

Drewness
Drewness

Reputation: 5072

() match group.

?: make the expression "non-capturing".

^ starts at the beginning of the string.

$ matches the end of the string.

| means "or".

\s matches whitespace.

+ greedy repetition. (see the link below for more info)

So put it all together and you get an expression that looks for whitespace at the beginning OR end of a string.

You can read more about fun with regular expressions here.

Upvotes: 2

KJC2009
KJC2009

Reputation: 59

The pattern ^\s+ will find leading whitespace,
and the pattern \s+$ will find trailing whitespace.

Hope you find that helpful.

You can read more about fun with regular expressions.

Upvotes: 0

TotoroTotoro
TotoroTotoro

Reputation: 17622

This regex has two main parts, separated by |. It means that any string will be a match if it matches either (?:^\s+) or (?:\s+$).

^\s+ means "one or more whitespace symbols at the beginning of string".

\s+$ means "one or more whitespace symbols at the end of string".

Any substring matching a regex inside (?:) will be saved for future use (it's called a match group). If all you need is to see if there's a match or not, you don't need to worry about it. In this case you can rewrite the regex as ^\s+|\s+$

Upvotes: 0

CAustin
CAustin

Reputation: 4614

You don't actually need to group anything with (?:). The pattern ^\s+|\s+$ will work just as well. Also, you might want to be wary of using \s in this case (in lieu of [ \t] for example), since it will also match newline characters (although this might be desired if you need to search for trailing newlines).

Upvotes: 1

Related Questions