Cjmarkham
Cjmarkham

Reputation: 9681

Regex to match string with or without capturing group

I've been trying for a while and not sure what to Google but I want both of these to be matched

Someone does something

and

Someone tries to do something

What I thought would work is

/^Someone (tries to)? do(es)? something$/

But that only matches the second string.

They are separate strings, not a single string spanning multiple lines.

Upvotes: 2

Views: 44

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

/^Someone(?: tries to)? do(?:es)? something$/

See proof

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  Someone                  'Someone'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
     tries to                ' tries to'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
   do                      ' do'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    es                       'es'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
   something               ' something'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

Upvotes: 1

Related Questions