0

The test string "aa" starts with 'a', also ends with 'a', why still no match found? How to understand the anchor "^" and "$" ?

Jacky
  • 147
  • 1
  • 2
  • 7

3 Answers3

1

The "^" matches the beginning of an input e.g. /^A/ matches the A in "An animal". "$" matches the end of an input e.g. /t$/ matches t in "statement". Your regex, ^a$ failed because the same character doesn't exist both at the start AND at the end of your string.

1

^ Asserts position at the start of the string.

$ Asserts position at the end of the string.

To match 2 times a, this might be an option:

^a{2}$ or ^aa$

This page about anchors might be helpful.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

+The "^" asserts the start of the string and "$" asserts the end.

You are saying, "match as string that starts, has one 'a' then ends.

If you want it to capture multiple 'a's too, then something like `/^a+$/ should do it.

Kevin
  • 359
  • 2
  • 7
  • 22
  • I'd suggest changing `*` to `+` since `*` matches nothing, thus, an empty string would be matched by your regex. Also, please use [markdown](https://stackoverflow.com/editing-help) in your answer – ctwheels Feb 21 '18 at 19:53
  • I would also suggest you use better terminology than `string that starts` since every string ever created `starts`. That seems a little broad to me. – ctwheels Feb 21 '18 at 19:55
  • Sorry ctwheels, I must have been making that edit while you were making that comment. – Kevin Feb 21 '18 at 21:07