We have seen that, we are using *
, +
, .
, $
, etc for different purposes. Now, if we want to match them themselves, we have to escape them using escape character(backslash-\) .
Below is the table for these kind of characters and their escaped version, along with their usages.
Character | Usage | Escaped version |
\ | escape character | \\ |
. | predefined character class | \. |
| | OR operator | \\ |
* | as quantifier | \* |
+ | as quantifier | \+ |
? | as quantifier | \? |
^ | boundary matcher | \^ |
$ | boundary matcher | \$ |
{ | in quantifier notation | \{ |
} | in quantifier notation | \} |
[ | in character class notation | \[ |
] | in character class notation | \] |
( | in group notation | \( |
) | in group notation | \) |
- | range operator | NA |
Sometimes, it is also preferred to use escaped forward slash(/
).
Predict the output of the following regex:
RegEx: \b(0|(1(01*0)*1))*\b
Text: This RegEx denotes the set of binary numbers divisible by 3:
0,11,1010, 1100, 1111, 1001
Answer:
Find a regular expression to match whole lines in the text containing either Apple, Orange, Grape as a word.
Hint: Use ^
and $
to match whole lines.
Answer: ^.*\b(apple|orange|grape)\b.*$
Find an expression which matches cat.
, 896.
, ?=++
but not abc1
.
Answer: ...\W