-3

I'm trying to come up with a regex that will match the entirety of the tag that has "ThisIsImportant" (including the tags themselves), without matching either of the other ones:

<tag>
  <random attribute="ThisIsNotImportant" />
</tag>

<tag>
  <random attribute="ThisIsImportant" />
</tag>

<tag>
  <random attribute="ThisIsAlsoNotImportant" />
</tag>

So far I've got "<tag>.*?</tag>", but I don't know how to make it so that I only match the one with "ThisIsImportant". Can anyone provide some help?

Thanks in advance.

EDIT: For clarity, I want to match the entirety of "<tag><random attribute="ThisIsImportant" /></tag>".

I am trying to do this in Bash using the perl executable, and am avoiding something like xmlstarlet because the environments I need to run the script on does not have access to this application.

8
  • 2
    Which programming language or tool are you doing this in? Please edit your question and add the appropriate tag. Commented Nov 17, 2015 at 2:13
  • I have added the requested information Commented Nov 17, 2015 at 2:16
  • 1
    You know that regex is particularly ill-suited to parsing HTML, right?? If you're programming in perl, is XML::DOM or Mojo::DOM not an option? If you're programming in bash, are you doing so by choice? And .. what have you tried? We can't help you fix code we haven't seen. Commented Nov 17, 2015 at 2:22
  • 2
    It has been said here over and over again, if you're processing XML then use an XML parser. Regular expressions are good for many things, but cannot process irregular syntaxes Commented Nov 17, 2015 at 2:23
  • What do you mean by tags themselves ? Are you looking for just the tag that has that attribute value, or are you looking for a closing tag, and all between as well ? Commented Nov 17, 2015 at 2:27

1 Answer 1

0

To get the closest starting tag to ThisIsImportant use a negative
assertion on the tag itself.

/<tag>(?:(?!<tag>).)*ThisIsImportant.*?<\/tag>/

Formatted:

 <tag>
 (?:
      (?! <tag> )
      . 
 )*
 ThisIsImportant
 .*? 
 </tag> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.