Course of Raku / Regexes and grammars / Regexes / Quantifiers / Exercises / An optional sign

Solution: An optional sign

Here is a possible solution to the task.

Code

say '-42' ~~ / '-'? \d+ /;

🦋 You can find the source code in the file optional-sign.raku.

Output

「-42」

Comments

  1. The '-'? part matches an optional minus sign — zero or one of them.

  2. \d+ then matches the run of digits. The same pattern also matches a number with no sign, such as 42.

Course navigation

An optional sign   |   Two to four digits