Here’s a problem I ran into recently. I have attributes strings of the form
'x=1 and y=abc and z=c4g and ...'
Some attributes have numeric values, some have alpha values, some have mixed, some have dates, etc.
Every string is supposed to have ‘x=someval and y=anotherval‘ at the beginning, but some don’t. I have three things I need to do.
- Validate the strings to be certain that they have
xandy. - Actually parse the values for
xandy. - Get the rest of the string.
Given the example at the top, this would result in the following variables:
$x = 1; $y = 'abc'; $remainder = 'z=c4g and ...'
My question is: Is there a (reasonably) simple way to parse these and validate with a single regular expression? i.e.:
if ($str =~ /someexpression/) { $x = $1; $y = $2; $remainder = $3; }
Note that the string may consist of only x and y attributes. This is a valid string.
I’ll post my solution as an answer, but it doesn’t meet my single-regex preference.
I’m not the best at regular expressions, but this seems pretty close to what you’re looking for:
Except you use $1, $2, and $4. In use:
Output:
This of course leaves out plenty of error checking, and I don’t know everything about your inputs, but this seems to work.