Search code examples
javascriptregexecmascript-6greasemonkey

Ignore String Between Two RegEx Matches


I have the following RegEx:

/Name:\s+(.*)\s+Company:\s+(.*)\s+Email:\s+(.*)\s+Phone:\s+(.*)\s+Inquiry:\s+(.*)\s+Comments:\s+(.*)/g

I am testing it against the following which matches:

Name: London Brown
Company: Amazon.com
Email: london@example.com
Phone: 2065550000
Inquiry: Technical
Comments: Example comment

I would like to modify this RegExp to ignore "Inquiry: Technical" whether it's present in the string or not as this data is sometimes present and sometimes isn't. Such that, the following will also be accepted:

Name: London Brown
Company: Amazon.com
Email: london@example.com
Phone: 2065550000
Comments: Example comment

Since this is a greasemonkey script, I have no control over the source data.


Solution

  • You might use an optional non capturing group (?:Inquiry:\s+(.*)\s+)?

    For example

    Name:\s+(.*)\s+Company:\s+(.*)\s+Email:\s+(.*)\s+Phone:\s+(.*)\s+(?:Inquiry:\s+(.*)\s+)?Comments:\s+(.*)
    

    Regex demo