Struct Template

Source
pub struct Template { /* private fields */ }
Expand description

A Template represents a string template with operations that can be applied to format input strings.

It allows defining a sequence of operations to transform input strings, such as splitting, joining, replacing, trimming, and more. The template is parsed from a string format that specifies the operations in a concise syntax.

The template syntax supports a variety of operations, including:

  • Split
  • Join
  • Substring extraction
  • Sed-like replacement using regex
  • Uppercase and lowercase conversion
  • Trimming whitespace or custom characters
  • Appending or prepending text
  • Map (apply sub-pipeline to each list item)
  • Sort, reverse, unique, pad, regex_extract

A Template can be created by parsing a string that follows the defined syntax (see Template::parse), and it can then be used to format input strings by applying the specified operations in sequence.

§Example

Trim, split and append a suffix to each resulting item:

use string_pipeline::Template;

let template = Template::parse("{split:,:..|map:{trim|append:!}}").unwrap();

let result = template.format(" a, b,c , d , e ").unwrap();

assert_eq!(result, "a!,b!,c!,d!,e!");

§Example: Map, Sort, Pad, Regex Extract

use string_pipeline::Template;

let template = Template::parse("{split:,:..|map:{upper}|sort:desc|join:-}").unwrap();
let result = template.format("a,b,c").unwrap();
assert_eq!(result, "C-B-A");

let template = Template::parse("{split:,:..|map:{pad:3:*:both}}").unwrap();
let result = template.format("a,bb,c").unwrap();
assert_eq!(result, "*a*,bb*,*c*");

let template = Template::parse("{split:,:..|map:{regex_extract:\\d+}}").unwrap();
let result = template.format("a1,b22,c333").unwrap();
assert_eq!(result, "1,22,333");

Implementations§

Source§

impl Template

Source

pub fn parse(template: &str) -> Result<Self, String>

Attempts to Parse a template string into a Template object.

Templates are enclosed in {} and consist of a chain of operations separated by |. Arguments to operations are separated by :.

§Syntax Reference
  • Template: { [!] operation_list? }
    • Add ! after { to enable debug mode.
  • Operation List: operation ('|' operation)*
  • Operation:
    • split:<sep>:<range>
      • Shorthand for split:
        • {index} (e.g. {1}, equivalent to {split: :1})
        • {range} (e.g. {1..3}, equivalent to {split: :1..3})
    • join:<sep>
    • substring:<range>
    • replace:s/<pattern>/<replacement>/<flags>
    • upper
    • lower
    • trim[:left|right|both]
    • strip:<chars>
    • append:<suffix>
    • prepend:<prefix>
    • strip_ansi
    • filter:<regex_pattern>
    • filter_not:<regex_pattern>
    • slice:<range>
    • map:{<operation_list>}
    • sort[:asc|desc]
    • reverse
    • unique
    • pad:<width>[:<char>][:left|right|both]
    • regex_extract:<pattern>[:<group>]
§Supported Operations
OperationSyntaxDescription
Splitsplit:<sep>:<range>Split by separator, select by index/range
Joinjoin:<sep>Join a list with separator
Substringsubstring:<range>Extract substring(s) by character index/range
Replacereplace:s/<pattern>/<replacement>/<flags>Regex replace (sed-like, supports flags)
UppercaseupperConvert to uppercase
LowercaselowerConvert to lowercase
Trim`trim[:leftright
Stripstrip:<chars>Strip custom characters from both ends
Appendappend:<suffix>Append text
Prependprepend:<prefix>Prepend text
StripAnsistrip_ansiRemove ANSI escape sequences
Filterfilter:<regex_pattern>Keep only items matching regex pattern
FilterNotfilter_not:<regex_pattern>Remove items matching regex pattern
Sliceslice:<range>Select elements from a list by index/range
Mapmap:{<operation_list>}Apply a sub-pipeline to each list item
Sort`sort[:ascdesc]`
ReversereverseReverse string or list
UniqueuniqueRemove duplicate items from a list
Pad`pad:[:][:leftright
RegexExtractregex_extract:<pattern>[:<group>]Extract first match or group from string/list items
§Range Specifications

Ranges use Rust-like syntax and support negative indices like Python:

RangeDescriptionExample
NSingle index{split:,:1} → second element
N..MExclusive range{split:,:1..3} → elements 1,2
N..=MInclusive range{split:,:1..=3} → elements 1,2,3
N..From N to end{split:,:2..} → from 2nd to end
..NFrom start to N{split:,:..3} → first 3 elements
..=NFrom start to N inclusive{split:,:..=2} → first 3 elements
..All elements{split:,:..} → all elements

Negative indices count from the end:

  • -1 = last element
  • -2 = second to last element
  • -3.. = last 3 elements
§Escaping

The parser intelligently handles pipe characters (|) based on context:

Pipes are automatically allowed in:

  • Split separators: {split:|:..} (splits on pipe)
  • Regex patterns: {filter:\.(txt|md|log)} (alternation)
  • Sed replacements: {replace:s/test/a|b/} (pipe in replacement)

Manual escaping needed for:

  • Other arguments: Use \| for literal pipes in join, append, prepend, etc.
  • Special characters: Use \: for literal colons, \\ for backslashes
  • Escape sequences: Use \n, \t, \r for newline, tab, carriage return
§Enable Debug Mode
  • Add ! after { to enable debug output for each operation:
  • Example: {!split:,:..|upper|join:-}
Source

pub fn format(&self, input: &str) -> Result<String, String>

Formats the input string using the operations defined in the template.

§Example
use string_pipeline::Template;

// Create a template that splits a string by commas, takes the first two items, and joins
// them with " and "
let template = Template::parse("{split:,:0..2|join: and }").unwrap();

// Format a string using the template
let result = template.format("a,b,c,d").unwrap();

assert_eq!(result, "a and b");

Trait Implementations§

Source§

impl Debug for Template

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Template

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl TryFrom<&str> for Template

Source§

type Error = String

The type returned in the event of a conversion error.
Source§

fn try_from(template: &str) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.