DEV Community

Discussion on: Asking for review on non-string regular expressions

Collapse
 
anpos231 profile image
anpos231

Maybe I fail to understand, but how is this:

from nsre import *

re = AnyNumber(
    Symbol(KeyHasValue("type", "image")) + Maybe(KeyHasValue("type", "caption"))
) + Range(KeyHasValue("type", "text"), min=1)

assert re.match(
    [
        {"type": "image", "url": "https://img1.jpg"},
        {"type": "image", "url": "https://img2.jpg"},
        {"type": "image", "url": "https://img3.jpg"},
        {"type": "caption", "text": "Image 3"},
        {"type": "image", "url": "https://img4.jpg"},
        {"type": "caption", "text": "Image 4"},
        {"type": "image", "url": "https://img5.jpg"},
        {"type": "text", "text": "Hello"},
        {"type": "text", "text": "Foo"},
        {"type": "text", "text": "Bar"},
    ]
)

Better than this:

[
  {"type": "image", "url": "https://img1.jpg"},
  {"type": "image", "url": "https://img2.jpg"},
  {"type": "image", "url": "https://img3.jpg"},
  {"type": "caption", "text": "Image 3"},
  {"type": "image", "url": "https://img4.jpg"},
  {"type": "caption", "text": "Image 4"},
  {"type": "image", "url": "https://img5.jpg"},
  {"type": "text", "text": "Hello"},
  {"type": "text", "text": "Foo"},
  {"type": "text", "text": "Bar"},
]
  .filter(x => (x.type === "image") || (x.type === "caption"))
  .filter(x => x.text)
  .map(x => x.text.length)