Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to split a string on multiple single‑character delimiters (and keep them) in Rust

1 Answer

0 votes
use regex::Regex;

fn split_keep_delims(s: &str, delimiters: &str) -> Vec<String> {
    // Build regex: e.g. ",;|" → "([,;|])"
    let pattern = format!("([{}])", regex::escape(delimiters));
    let re = Regex::new(&pattern).unwrap();

    let mut result = Vec::new();
    let mut last_end = 0;

    for m in re.find_iter(s) {
        let start = m.start();
        let end = m.end();

        // Add text before delimiter
        if start > last_end {
            result.push(s[last_end..start].to_string());
        }

        // Add the delimiter itself
        result.push(s[start..end].to_string());

        last_end = end;
    }

    // Add remaining text after last delimiter
    if last_end < s.len() {
        result.push(s[last_end..].to_string());
    }

    result
}

fn main() {
    let input = "aa,bbb;cccc|ddddd";
    let parts = split_keep_delims(input, ",;|");

    for p in parts {
        print!("[{}] ", p);
    }
}




/*
run:

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...