I want to match an xml element and create a group for an optional attribute. If the attribute does not exist then i’m going to perform some other action. For example i have
<customer display="no">
I want to match on the customer element but the display attribute might not exist. In code i was going to check to see if that capture group is empty and if so perform some custom logic.
so the regex i have is
<customer.*(display="yes|no").*?>
That matches the element ok when it has the attribute but how can i make the group optional so i can check to see if the element was included?
You can just put a question mark after the group, the same as any other optional component of a regex. You will also have to make the first
.*lazy (by adding?) if you do this, otherwise it will consume the whole line.So you should have something like this:
Also note that
(display="yes|no")probably doesn’t match what you want it to: it matchesdisplay="yesorno"notdisplay="yes"ordisplay="no". I suspect you want(display="(?:yes|no)")instead.