12.5. Escape Character¶
Since we use special characters in regular expressions to match the beginning or end of a line or specify wild cards, we need a way to indicate that these characters are “normal” and we want to match the actual character such as a dollar sign or caret.
We can indicate that we want to simply match a character by prefixing that character with a backslash. For example, we can find money amounts with the following regular expression.
Since we prefix the dollar sign with a backslash, it actually matches the dollar sign in the input string instead of matching the “end of line”, and the rest of the regular expression matches one or more digits or the period character.
Note
Inside square brackets, characters are not “special”. So when we say [0-9.]
,
it really means digits or a period. Outside of square brackets, a period is the “wild-card”
character and matches any character. Inside square brackets, the period is a period.
Change the regex equation so that it matches with the math equation in the given string ‘x’.
- .
- This will trigger the wild-card function.
- /.
- This will not work.
- \.
- This is the correct usage of the backslash.
- |.
- Try again! In regex, | is used to match the expression on the left or the expression on the right
11-9-3: How do we match a period (and not a wild-card) in a string using regex?
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.