You've mentioned in comments that you want something portable. That's admirable, but I'd really urge you to not do that anyway.
XML is a contextual language, and regex isn't. There's simply no way a regular expression can parse XML correctly as a result.
At best - you get a hack, that's only valid provided the XML stays in the same format. But as the XML spec says that format can chance and retain the same semantics, that's a dangerous assumption and creates brittle code.
I know you have reasons to want to do this - you already have an answer that gives you a way to. I would suggest that a parser is still the right answer.
But with XML parsers, you get
xpath - which is a lot like regular expressions, but is applicable to hierarchical information.
Something like this:
my $twig = XML::Twig -> parse ( \*DATA );
my $version = $twig -> get_xpath('//item/artifactId[string()="myproject"]/../version',0)->text;
Hopefully you can see how that
xpath is working?
//item finds an item anywhere within the structure.
[string()= queries the text content. You could instead do something like
[@someAtt="fish"] to check an attribute.
.. up (to
item) and get the
Then get the
As a oneliner:
perl -MXML::Twig -0777 -e 'print XML::Twig -> parse ( <> ) -> get_xpath('/item/artifactId[string()="myproject"]/../version',0)->text,"\n" yourxmlfile.xml
Now, I'm suggesting
XML::Twig because I think it's easier to learn.
XML::LibXML is also quite good.
But it's distributed with strawberry perl on Windows, and is readily available in a lot of package managers - or from
xmlstarlet should allow you to do much the same thing.