Rust Regex
crate没有环顾四周,所以我不能使用{
的负面后瞻和}
的否定前瞻。
我试过了:
extern crate regex;
use regex::Regex;
fn main() {
let exp = Regex::new("(?:[^{]|^)\\{([^{}]*)\\}").unwrap();
let text = "{this} is a match, {{escaped}} is not, but {these}{also} are.";
for capture in exp.captures_iter(text) {
println!("{}", &capture[1]);
}
// expected result: "this", "these", "also"
}
这不会捕获"also"
,因为匹配不重叠。有没有办法在没有环顾四周的情况下这样做?
答案 0 :(得分:4)
您可以使用丢弃技术并使用如下模式:
{{|}}|{([^}]+)}
<强> Working demo 强>
如果您需要匹配字母数字和下划线
,则更容易阅读{{|}}|{(\w+)}
在您的代码中,您现在必须检查是否存在匹配的组1:
extern crate regex;
use regex::Regex;
fn main() {
let exp = Regex::new(r"\{\{|\}\}|\{([^}]+)\}").unwrap();
let text = "{this} is a match, {{escaped}} is not, but {these}{also} are.";
for capture in exp.captures_iter(text) {
if let Some(matched) = capture.get(1) {
println!("{}", matched.as_str());
}
}
// printed: "this", "these", "also"
}