regex optional word match

You can enclose the part you want to match in a non-capturing group: (?:). Then it can be treated as a single unit in the regex, and subsequently you can put a ? after it to make it optional. Example:

/Singers?:(.*)\s?(?:Lyricists?:(.*))?/

Note that here the \s? is useless since .* will greedily eat all characters, and no backtracking will be necessary. This also means that the (?:Lyricists?:(.*)) part will never be matched for the same reason. You can use the non-greedy version of .*, .*? along with the $ to fix this:

/Singers?:(.*?)\s*(?:Lyricists?:(.*))?$/

Some extra whitespace ends up captured; this can be removed also, giving a final regex of:

/Singers?:\s*(.*?)\s*(?:Lyricists?:\s*(.*))?$/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)