我想确定某个字符串是否包含某个子字符串,同时考虑组合字符。为了说明这个问题,请考虑以下 Rust 示例:
\nfn main() {\n let a_umlaut = "a\\u{0308}"; // "\xc3\xa4"\n println!("{}", a_umlaut.starts_with("a")); // true\n}\nRun Code Online (Sandbox Code Playgroud)\n基本上,上面的内容表明这"\xc3\xa4".starts_with("a")是正确的(注意第一个“a”上的分音符)。我确实在技术层面上理解这种行为的原因,但我仍然希望上面的代码输出false,因为“\xc3\xa4”和“a”是两个不同的用户感知字符。
是否有现有的函数/创建在尊重组合字符的同时执行字符串匹配?
\n我从我的评论中扩展了我的想法。此正则表达式将匹配字符串的开头(a没有变音符号的字符)。
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}\nRun Code Online (Sandbox Code Playgroud)\n输出:
\nOriginal 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\nRun Code Online (Sandbox Code Playgroud)\n\n这里的想法是,您可以扩展您不想在正则表达式中匹配的字符列表,因此a也会列出任何可以与之组合的字符。这确实遇到了一个问题,即这可能是一个很长的列表,但如果这是一个受约束的问题,那么这种方法就可以工作。