Require at least one word boundary

Viewed 106

I am looking to create a regex that allows either one or two word boundaries, but not zero.

For example, for the word term:

  • a term is <-- yes, space before and space after (two boundaries)
  • the terms are <-- yes, space before (one boundary)
  • the midterm was <-- yes, space after (one boundary)
  • the midterms were <-- no (zero word boundaries)

Would would be the best regex for this? My initial thinking was:

But this seems way too verbose. What might be a better one?

1 Answers

Use a conditional:

(\b)?term(?(1)|\b)

See proof. If there is a word boundary in front, do not enforce it at the end. Else, require a word boundary at the end.

If a conditional is not available, use alternation:

\bterm|term\b

See another proof.

Related