user495847
user495847

Reputation: 129

What does this regular expression mean?

In a recent interview I was asked to decipher this regex

^\^[^^]

Can you please help me with it. Also please provide some links where I can learn regex for interviews.

Upvotes: 12

Views: 2019

Answers (4)

codaddict
codaddict

Reputation: 454960

It matches strings that begin with ^ followed by any character other than ^.

So it would match:

^foo
^b

but not

foo
^^b

Explanation:

Caret (^) is a regex meta character with two different meanings:

Outside the character class(1st use in your regex) it works as start anchor.

Inside the character class it acts like negator if used as the first character of the character class(3rd use in your regex).

Preceding a regex with \ escapes it (makes it non-special). The 2nd use of ^ in your regex is escaped and it matches a literal ^ in the string.

Inside a character class a ^ which is not the first character of the character class is treated literally. So the 4th use in your regex is a literal ^.

Some more examples to make it clear:

  • ^a         : Matches string beginning with a
  • ^ab       : Matches string beginning with a followed by b
  • [a]       : Matches a string which has an a
  • [^a]     : Matches a string which does not have an a
  • ^a[^a] : Matches a string beginning with an a followed by any character other than a.

Upvotes: 30

Philar
Philar

Reputation: 3897

I'm testing this regex here however it does not seem to be valid.
The first ^ denotes the start of the line.
The first \ escapes the following \.
Thus the second "^" is not escaped Finally the first caret inside the square brackets [^ acts as the negation and second one ^] is not escaped as a result is not valid.

IMHO the correct regexp should be ^\^[^\^]
Guys, kindly confirm. Many thanks

Upvotes: 3

nonopolarity
nonopolarity

Reputation: 150976

The first ^ is the beginning of line.

The second one is a literal character of ^ (\ is to escape the other usual meaning of ^)

The third one is to say

a class of characters which does not include the character ^

Some example to show using Ruby:

ruby-1.9.2-p0 > "hello" =~ /^h/    # it found a match at position 0
 => 0 

ruby-1.9.2-p0 > "hello" =~ /^e/    # nil means can't find it
 => nil 

ruby-1.9.2-p0 > "he^llo" =~ /\^/   # found at position 2
 => 2 

ruby-1.9.2-p0 > "he^llo"[/[^^]*/]  # anything repeatedly but not including the ^ character
 => "he" 

Upvotes: 2

Mike Cheel
Mike Cheel

Reputation: 13106

Match beginning of line or string followed by a literal \ followed by the beginning of the line or string followed by any character that is not a space, return or new line character

Upvotes: 2

Related Questions