vregex 0.7.0

Regular Expression engine
Documentation
use crate::types::re;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
/// WASM wrapper for the `RegEx` struct
pub struct RegEx {
    engine: re::RegEx,
}

#[wasm_bindgen]
impl RegEx {
    #[wasm_bindgen(constructor)]
    /// Returns a RegEx object, or throws an error if the given pattern has an incorrect syntax
    ///
    /// # Syntax
    /// - `.` matches any character.
    /// - `|` is used for alternate: `a|b` matches `a` or `b`.
    /// - `[]` is used for defining classes: `[abc]` matches any of the characters within.
    /// - Use `^` at the beginning of a class to make it exclusive: `[^abc]` matches everything but `a`, `b`, or `c`.
    ///
    /// There are also character classes available. Lowercase classes are inclusive, uppercase are exclusive.
    /// - `\d`, and `\D` for digits.
    /// - `\l`, and `\L` for lowercase characters.
    /// - `\u`, and `\U` for uppercase characters.
    /// - `\s`, and `\S` for whitespace.
    pub fn new(pattern: &str) -> Result<Self, String> {
        Ok(Self {
            engine: re::RegEx::from_pattern(pattern).map_err(|e| format!("{:#?}", e))?,
        })
    }

    #[wasm_bindgen]
    /// Returns the index of the first match with the regular expression within the given string, or `undefined` if there are none.
    pub fn search(&self, string: &str) -> Option<u32> {
        self.engine.search(string).map(|v| v as u32)
    }
}