Newbie
Newbie

Reputation: 167

What does this regular expression mean? (^.)(\w+)(.$) $2

(^.)(\w+)(.$) $2 removes first and last char, but I'm not sure how does it work.

My understanding:

(^.) match any one character at the start of the line. (.$) match any one character at the end of the line. (\w+) any word character(at least one character is required) $2 calls the second parentheses (\w+)

Test1:

Input: 91239

Output: 123

Test2:

Input: \123\

Output: 123 

Why does it remove the backslash? Is this a acceptable way to remove the backslash(begin and end of the line)?

Test3:

Input: /123/5

Output: /123/5

I'm lost here. Why it doesn't work for /123/5.

Thank you!

Upvotes: 0

Views: 1013

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

Why it doesn't work for /123/5.

\w is equivalent to [a-zA-Z0-9_] and . matches any character.. so in /123/5.. / before 1 is matched by ^. and 5 is matched by .$ but 123/ is not matched since / is not a matched by \w

Regex (^.)(\w+)(.$) means (Explanation):

  • (^.) start with any character (parenthesis => capture group 1)
  • (\w+) followed by more than one (+) characters in the set [a-zA-Z0-9_] (parenthesis => capture group 2)
  • (.$) end with any character (parenthesis => capture group 3)

And finally $2 means backreference to capture group 2.. i.e group captured by pattern (\w+).

Upvotes: 1

Politank-Z
Politank-Z

Reputation: 3719

Why does it remove the backslash? Is this a acceptable way to remove the backslash(begin and end of the line)?

It removes the backslashes because . matches any character, including \. Group 1 is the first backslash, group 2 is every character but the first and last, group 3 is the last backslash.

I'm lost here. Why it doesn't work for /123/5.

\w matches 0-9, a-z, A-Z, and _. \w+ consumes 123. The following . consumes /. The following $ doesn't match the remaining 5, thus there is no match with that input.

Upvotes: 2

Related Questions