-5

how to write one regular express for cpp or h? I want to match the word cpp or h?

jiafu
  • 6,338
  • 12
  • 49
  • 73

2 Answers2

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

DEMO

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 the h in cph. 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 matches h 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.

Community
  • 1
  • 1
zx81
  • 41,100
  • 9
  • 89
  • 105