Search code examples
regexcapturing-group

Regex non-greedy named capturing groups


I need to parse the below text and read the value for id and name, and name is optional. I am getting 'txt" name="thistext' as the value for id.

input id="txt" name="thistext"

This is the regex I am using -

input\s+id="(?<id>.*)("+?)(?:(\s+name="(?<name>.*)(.*?")))?

Full match 0-30 input id="txt" name="thistext" Group id 10-29 txt" name="thistext Group 2. 29-30 "


Solution

  • Your regex was almost correct except, you needed to do non-greedy capture in your id named group and change your regex to this,

    input\s+id="(?<id>.*?)("+?)(?:(\s+name="(?<name>.*)(.*?")))?
    

    Demo

    Also, your regex is uselessly overly complex which you can simplify as this,

    input\s+id="(?<id>[^"]*)"(?:\s+name="(?<name>[^"]*)")?
    

    Demo for better regex