Rust:Unicode 感知的字符串匹配

Dav*_*iD. 5 unicode rust

我想确定某个字符串是否包含某个子字符串,同时考虑组合字符。为了说明这个问题,请考虑以下 Rust 示例:

\n
fn main() {\n    let a_umlaut = "a\\u{0308}"; // "\xc3\xa4"\n    println!("{}", a_umlaut.starts_with("a")); // true\n}\n
Run Code Online (Sandbox Code Playgroud)\n

基本上,上面的内容表明这"\xc3\xa4".starts_with("a")是正确的(注意第一个“a”上的分音符)。我确实在技术层面上理解这种行为的原因,但我仍然希望上面的代码输出false,因为“\xc3\xa4”和“a”是两个不同的用户感知字符。

\n

是否有现有的函数/创建在尊重组合字符的同时执行字符串匹配?

\n

Kev*_*son 0

我从我的评论中扩展了我的想法。此正则表达式将匹配字符串的开头(a没有变音符号的字符)。

\n
use regex::Regex;\n\nfn main() {\n    let a_umlaut = "a\\u{0308}"; // "\xc3\xa4"\n    println!("Original string: {}", a_umlaut);\n    println!("Start with regular \'a\': {}", a_umlaut.starts_with("a")); // true\n\n    let re = Regex::new(r"^a[^\\u{0308}]").unwrap(); // Matches non-combined "a" at the front\n    tester(&re, a_umlaut);      // "a" with umlaut behind\n    tester(&re, "blessed are"); // "a" in the middle, not the front\n    tester(&re, "amore!");      // "a" at the front\n\n}\n\nfn tester(re: &Regex, test: &str)\n{\n    println!("For string: \'{}\' with Regex: \'{}\', match is: {}", test, re.as_str(), re.is_match(test));\n}\n
Run Code Online (Sandbox Code Playgroud)\n

输出:

\n
Original string: a\xcc\x88\nStart with regular \'a\': true\nFor string: \'a\xcc\x88\' with Regex: \'^a[^\\u{0308}]\', match is: false\nFor string: \'blessed are\' with Regex: \'^a[^\\u{0308}]\', match is: false\nFor string: \'amore!\' with Regex: \'^a[^\\u{0308}]\', match is: true\n
Run Code Online (Sandbox Code Playgroud)\n

游乐场链接

\n

这里的想法是,您可以扩展您不想在正则表达式中匹配的字符列表,因此a也会列出任何可以与之组合的字符。这确实遇到了一个问题,即这可能是一个很长的列表,但如果这是一个受约束的问题,那么这种方法就可以工作。

\n