0

I have a list that I'm trying to filter.

I'm planning to separate a string into parts of the string that matches a pattern and parts that doesn't.

Like if the string is:

<h1>hello</h1>

the list would be:

['<h1>', 'hello', '</h1>']

I'm currently using split() to separate the preceding pattern, but the pattern separating them gets included in the entry for the patterns that don't match.

I'm going to use a for loop to iterate through them to separate the pattern from the ones that doesn't.

6
  • I believe we need more context to answer your question. Is the list in a buffer? Is the list a vimscript object? I suppose an example of input an desired output would help. Jul 23, 2023 at 10:06
  • Just added more details. Jul 23, 2023 at 10:28
  • please explain exactly what you are trying to achieve what you tried, what you expected and what happens instead. Jul 23, 2023 at 10:41
  • Sorry. I think I just did that. I'm not sure if you saw the new revisions already, or you saw the old version of the question. Jul 23, 2023 at 10:43
  • What pattern have you tried? Jul 23, 2023 at 10:43

2 Answers 2

1

To split the string:

<h1>hello</h1>

Into:

['<h1>', 'hello', '</h1>']

The proposition of @LucHermitte is

split('<h1>hello</h1>', '\v(\<[^<]*\>|[^<]+)\zs')

Where:

  • \v\<[^<]*\> match a tag
  • \v[^<]+ match a non tag
1
  • No. I mean a list like [1, 2, 3, 4, 5]. Jul 23, 2023 at 10:26
1
:echo split('123Hello!456World', '\v(\d+|\D+)\zs')

-> ['123', 'Hello!', '456', 'World']

Seems to do the job.

The secret is in: split(): "If you want to keep the separator you can also use '\zs' at the end of the pattern:"

7
  • It does! That's weird. Maybe my pattern for matching with HTML tags is wrong. I'm using :echo split('<h1>Hello!</h1>', '\<[^>]*>\zs') and it includes the terminal tag with Hello!. That's weird. I checked the regular expression on regexr.com and it works. Jul 23, 2023 at 10:52
  • My pattern is numbers (\d+) or not numbers (\D+). You'll have to play with negative patterns to handle HTML tags and non-HTML tags. I never remember how to achieve that on the first try. ^^' Jul 23, 2023 at 11:03
  • I'm sorry. You lost me. I'm new to regular expressions and I don't exactly understand what you mean. Does the negative pattern refer to the terminal tag that has a / or is it the non-tags? Jul 23, 2023 at 11:06
  • No. It refers to anything that doesn't match <[^>]*>. See , :h /\@!, :h /\@<!... They are really tricky to use right. Jul 23, 2023 at 11:09
  • They are. I'm still building my regular expressions using a tool. It's a trial-and-error basis for me. Jul 23, 2023 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.