esteban
esteban

Reputation: 308

Regex lookahead and behind?

So I have a unordered list that looks like:

<ul class='radio' id='input_16_5'>
<li>
    <input name='input_5' type='radio' value='location_1'  id='choice_16_5_0' />
    <label for='choice_16_5_0' id='label_16_5_0'>Location 1</label></li>
<li>
    <input name='input_5' type='radio' value='location_2'  id='choice_16_5_1' />
    <label for='choice_16_5_1' id='label_16_5_1'>Location 2</label></li>
<li>
    <input name='input_5' type='radio' value='location_3'  id='choice_16_5_2' />
    <label for='choice_16_5_2' id='label_16_5_2'>Location 3</label></li>
</ul>

I would like to pass a value (ie. location_2) to a regular expression that will then capture the whole list item that it's a part of in order to remove it. So if I pass it location_2 it will match the to the (including) <li> and the </li> of the list item that it's in.

I can match up to the end of the list item with /location_3.+?(?=<li|<\/ul)/ but is there something I can do to match before and not capture other items?

Upvotes: 0

Views: 62

Answers (1)

fronthem
fronthem

Reputation: 4139

This should get what you want

<li>(?:(?!<li>)[\S\s])+location_1[\S\s]+?<\/li>

Exaplanation

<li>: open li tag,

(?:(?!<li>)[\S\s])+: match for any characters including a newline and use negative look ahead to make sure that your highlight will not consume two or more <li> tags,

location_1: keyword that you use for highlight the whole <li> tag,

[\S\s]+?: any characters including a newline. (Here, thanks @Tensibai for your comment that make this regex be more simple with non-greedy)

<\/li> close li tag.

DEMO: https://regex101.com/r/cU4eC6/5

Additional information:

/<li>(?:(?!<li>).)+location_2.+?<\/li>/s

This regex is also work where you use modifier s to handle a newline instead of [\S\s]. (Thanks again to @Tensibai)

Upvotes: 1

Related Questions