Regex to capture string with multiple optional words

Viewed 32

I'm using Overpass API's regex. Unsure which flavour it uses.

I'm wishing to capture these strings:

"Footpath"
"Public Footpath"
"Footpath No. 27001"
"Public Footpath No. 125"
"Footpath #424"
"Public Footpath #5"

This fails to return the first two options.

^(Public)?Footpath (No\. |#)?[0-9]

How do I make the 'No./# optional? I've tried variations on wrapping them in brackets, but to no avail eg.

^(Public)?Footpath ((No\. |#)?[0-9])?

I'm afraid I'm out of my depth.

1 Answers

You may use this regex with multiple optional non-capturing groups:

^(?:Public )?Footpath(?: No\.)?(?: #?[0-9]+)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:Public )?: Match Public in an optional non-capturing group
  • Footpath: Match Footpath
  • (?: No\.)?: Match No\. in an optional non-capturing group
  • (?: #?[0-9]+)?: Match space followed by optional # and 1+ digits in an optional non-capturing group
  • $: End
Related