Explain the uses of caret(^) in regex

Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Pig Latin:

Please explain the uses of ^ (caret)
what does it match using the caret at different places like these:

  1. /([^aeiou])(.*)/
  2. /^([aeiou])(.*)/
    or
  3. /^([^aeiou])(.*)/
3 Likes

The caret serves two different purposes. It is a special character that denotes “the beginning of a line” and it is a “not” operator inside of []s.

  1. Matches any character that is not a vowel followed by any number of characters.
  2. Matches a vowel at the start of a line, followed by any number of characrters.
  3. Matches any character that is not a vowel, at the start of a line, followed by any number of characters.

regex101.com is a really convenient tool for breaking down the parts of your pattern.

5 Likes

What is the use of the parentheses?

1 Like

Parentheses in a regular expression usually indicate a ‘capture group’, or subset of the string to be stored for later reference. For example:

/^([aeiouy])(.)/

indicates a string starting with a single vowel (the first capture group is a single vowel), followed by any single character (the second capture group is any single character). How they get referenced elsewhere in the regex… Isn’t happening in this one. :wink:

2 Likes

Thanks for the reply.