std/regex

std/regex 模組基於 POSIX regex.h 提供正規表達式支援。

使用方法

import "std/regex.zc"
import "std/io.zc"

fn main() {
    if regex_match("^[a-z]+$", "hello") {
        println("匹配成功!");
    }
    
    let re = Regex::compile("\\d+");
    let count = re.count("123 abc 456");
    re.destroy();
}

結構體定義

Regex

代表一個已編譯的正規表達式。

struct Regex {
    // 內部句柄
}

Match

代表一個成功的正規表達式匹配結果。

struct Match {
    text: char*;
    start: int;
    len: int;
}

方法

正規表達式建構

方法簽名說明
compileRegex::compile(pattern: char*) -> Regex使用預設標誌編譯一個正規表達式模式。
compile_with_flagsRegex::compile_with_flags(pattern: char*, flags: int) -> Regex使用自定義 POSIX 標誌進行編譯。
destroydestroy(self)釋放已編譯的正規表達式。

匹配與搜尋

方法簽名說明
matchmatch(self, text: char*) -> bool如果模式在 text 中的任何位置匹配,則返回 true。
findfind(self, text: char*) -> Option<Match>返回包含位置和長度的第一個匹配結果。
countcount(self, text: char*) -> int返回不重疊的匹配次數。
splitsplit(self, text: char*) -> Vec<String>根據模式分割字串。

匹配內容存取

方法簽名說明
as_stringas_string(self) -> char*返回到匹配內容起始點的指標。
endend(self) -> int返回匹配內容最後一個字元之後的索引。

靜態輔助函數

方法簽名說明
regex_matchregex_match(pattern: char*, text: char*) -> bool快速檢查是否匹配。
regex_findregex_find(pattern: char*, text: char*) -> Option<Match>尋找第一個匹配結果。
regex_countregex_count(pattern: char*, text: char*) -> int統計所有匹配次數。
regex_splitregex_split(pattern: char*, text: char*) -> Vec<String>根據模式分割字串。