Skip to content

Split with matches #285

Closed
Closed
@Keats

Description

@Keats

I was trying to implement http://jinja.pocoo.org/docs/dev/templates/#title and I was surprised to realise that matches were not included on split like they are in js or python.
In JS:

"foo bar".split(/(\s+)/)
["foo", " ", "bar"]

Is it possible to get a split_including_matches that matches that behaviour?
My naive implementation of the filter was:

static ref WORD_BEGINNING_SPLIT_RE: Regex = Regex::new(r"([-\s\(\{\[<]+)").unwrap();

&WORD_BEGINNING_SPLIT_RE
        .split(&s)
        .map(|item| {
            let mut c = item.chars();
            match c.next() {
                None => "".to_string(),
                Some(f) => f.to_uppercase().collect::<String>() + &c.as_str().to_lowercase()
            }
        })
        .collect::<Vec<_>>()
        .join("")

but since it doesn't include the matches, if I join at the end I will have lost all the whitespaces.

The current implementation takes 50 lines to do that https://github.com/Keats/tera/blob/master/src/filters/string.rs#L105-L155

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions