-1

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 "

Indu
  • 99
  • 1
  • 1
  • 5

1 Answers1

1

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

Pushpesh Kumar Rajwanshi
  • 17,850
  • 2
  • 16
  • 35