I have a file, with some data.
I need the regex that matches a text only within the Title=“”, but ignore if the text is within square brackets, and not others for ex. Link, BreakType etc
The word i want to match is Color.
<TocEntry
Title="Color" - Highlight this text Color
Title=["Color"] - Ignore this text Color
Link="/Content/Color/" - ignore this text Color
BreakType="Color" - ignore this text Color
StartSection="false"
PageNumberReset="Color"> - ignore this text Color
</TocEntry>
<TocEntry
Title="Colord"> - ignore this text Colord
//there could be Link="abc", BreakType="abc" here aswell
</TocEntry>
<TocEntry
Title="dColord"> - ignore this text dColord
</TocEntry>
<TocEntry
Title="my fav Color is red"> - Highlight this text Color
Title=["my fav Color is red"]> - - ignore this text Color
</TocEntry>
<TocEntry
Title="my fav
Color
is red"> - Highlight this text Color
</TocEntry>
>Solution :
If you’re looking to only match the word Color in those instances, this regex will work (run sample to view in action)
/(?<=Title="[^"]*)\bColor\b(?=[^"]*")/g
breakdown:
(?<=Title="[^"]*): positive lookbehind, ensure that the match is preceded by but does not include Title=" followed by 0 or more number of non-" characters
\bColor\b: match the word Color, but only if it has boundaries on both sides (not numbers or letters)
(?=[^"]*"): positive lookahead, ensure that the match is followed by but does not include any number of non-" characters followed by a single "
const input = `<TocEntry
Title="Color" - Highlight this text Color
Title=["Color"] - Ignore this text Color
Link="/Content/Color/" - ignore this text Color
BreakType="Color" - ignore this text Color
StartSection="false"
PageNumberReset="Color"> - ignore this text Color
</TocEntry>
<TocEntry
Title="Colord"> - ignore this text Colord
//there could be Link="abc", BreakType="abc" here aswell
</TocEntry>
<TocEntry
Title="dColord"> - ignore this text dColord
</TocEntry>
<TocEntry
Title="my fav Color is red"> - Highlight this text Color
Title=["my fav Color is red"]> - - ignore this text Color
</TocEntry>
<TocEntry
Title="my fav
Color
is red"> - Highlight this text Color
</TocEntry>`
const matches = input.match(/(?<=Title="[^"]*)\bColor\b(?=[^"]*")/g)
console.log(matches)
console.log(input.replace(/(?<=Title="[^"]*)\bColor\b(?=[^"]*")/g, '[MATCHED AND REPLACED]'))