The test string "aa" starts with 'a', also ends with 'a', why still no match found? How to understand the anchor "^" and "$" ?
Asked
Active
Viewed 48 times
0
-
1Your regex allows only single `a` – anubhava Feb 21 '18 at 19:48
-
Thanks, so how to understand anchors correctly? – Jacky Feb 21 '18 at 19:51
-
Your anchors are correct, you need to quantify `a`. Try `^a+$` (one or more `a`) – ctwheels Feb 21 '18 at 19:52
-
See https://regex101.com/r/8mdAL4/2/debugger, and you will see how the engine tries to match `aa` with `^a$`. It is impossible to match a 2-letter string with a pattern that can only match a 1 letter string. – Wiktor Stribiżew Feb 21 '18 at 20:39
3 Answers
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.

ProgrammerAdept
- 106
- 9
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:
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