How to search for a combination of words inside a nested bullet list in regex?

Viewed 81

I would like to search for a combination of two words (let’s say term1 and term2) inside a bullet list. The condition is that these two words have to be from the same nested list and that the search has to be for any combination of these two words. Nested lists are separated by two new lines \n.

The input text

- Example nested list 1
    - This point contains term 2
    - This point contains term 1

- Example nested list 2
    - This line contains term 2

In order to achieve this I first tried to capture different nested lists in different capture groups.

- ([\s\S]*?)\n\n

Now, I would like to search inside each of these capture groups but I can’t seem to find out how. An example regex is at https://regex101.com/r/OC6OI5/12

Edit: For people who are wondering why this might be useful, I’m trying to build a Roam Research like Linked references filtering in a markdown editor

1 Answers

If there should be only a single nested list, and the term 1 and term 2 should be both present, you could use 2 lookahead assertions (?=

You could start the match at the start of the string, and match all lines that start with -.

Then you can assert what follows are lines that all begin with 1 or more whitespace chars without a newline followed by -.

Use 2 positive lookaheads to assert both terms, and match all following lines that have that same indentation.

^(?:-.*\r?\n)+(?=(?:[^\S\r\n]+-.*\r?\n)*[^\S\r\n]+.*(term 1))(?=(?:[^\S\r\n]+-.*\r?\n)*[^\S\r\n]+-.*(term 2))(?:[^\S\r\n]+.*(?:\r?\n|$))+

Explanation

  • ^ Start of the string
  • (?:-.*\r?\n)+ Match 1+ times a line that starts with -
  • (?= Positive lookahead, assert what is on the right is
    • (?:[^\S\r\n]+-.*\r?\n)* Optionally repeat lines that start with whitespaces without newlines, then - and the rest of the line
    • [^\S\r\n]+-.*(term 1) Match a line that starts with 1+ whitespaces followed by - and contains term 1
  • ) Close lookahead
  • (?=(?:[^\S\r\n]+-.*\r?\n)*[^\S\r\n]+.*(term 2)) The same lookahead mechanism again for term 2
  • (?: Non capture group
    • [^\S\r\n]+-.*(?:\r?\n|$) Match a line that starts with 1+ whitespaces followed by - and the rest of the line
  • )+ Close the group and repeat 1+ more times

Regex demo

Related