how to write one regular express for cpp or h? I want to match the word cpp or h?
Asked
Active
Viewed 86 times
-5
-
3... so what's wrong with `cpp|h`? – tckmn Jul 18 '14 at 05:56
-
it seems match cpp or cph ,not cpp or h – jiafu Jul 18 '14 at 05:57
-
Which regex engine are you using? That doesn't seem right. In any case, just use parentheses: `(cpp)|(h)` – tckmn Jul 18 '14 at 05:58
-
should it be add ()? – jiafu Jul 18 '14 at 06:02
2 Answers
0
Use a non-capturing group,
(?:cpp|h)
Add word boundaries inorder to match cpp
or h
present just before and after to a non-word character.
\b(?:cpp|h)\b

Avinash Raj
- 172,303
- 28
- 230
- 274
0
Option 1: validate that a string is exactly cpp
or h
.
For this, use:
^h|cpp$
Explanation
- The reason why
cpp|h
"matches"cph
is that the engine is able to match theh
incph
. If you inspect whether a match is found, it will return True. - The
^
anchor asserts that we are at the beginning of the string h|cpp
matchesh
OR (|
)cpp
- The
$
anchor asserts that we are at the end of the string
Option 2: match h
or cpp
as independent words within text
For this, use:
\b(?:h|cpp)\b
which is essentially the same as the second option in Avinash's answer.