// s は Vec<u8>。もとからString であればこんなことしなくて良い。
let re = Regex::new(r"^<=+>$").unwrap();
let ans = re.is_match(&String::from_utf8(s.clone()).unwrap());
通常
let re = Regex::new(r"[^01]+").unwrap();
assert_eq!(re.replace("1078910234", ""), "1010234"); // 1回だけ replace する
assert_eq!(re.replace_all("1078910234", ""), "1010"); // 複数回 replace する
// 回数指定は replacen
例:
キャプチャーを使ったもの
let re = Regex::new(r"([^,\\s]+),\\s+(\\S+)").unwrap();
let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
format!("{} {}", &caps[2], &caps[1])
});
assert_eq!(result, "Bruce Springsteen");
let re = Regex::new(r"(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})").unwrap();
let before = "1973-01-05, 1975-08-25 and 1980-10-18";
let after = re.replace_all(before, "$m/$d/$y");
assert_eq!(after, "01/05/1973, 08/25/1975 and 10/18/1980");
replace の型はこう
pub fn replace<'h, R: Replacer>(
&self,
haystack: &'h str,
rep: R
) -> Cow<'h, str>
let re = Regex::new(r"\\b\\w{13}\\b").unwrap();
let hay = "I categorically deny having triskaidekaphobia.";
let mat = re.find(hay).unwrap();
assert_eq!(2..15, mat.range());
assert_eq!("categorically", mat.as_str());
場所が range で取得できる。マッチした文字列も取得できる。
let re = Regex::new(r"[0-9]{4}-[0-9]{2}-[0-9]{2}").unwrap();
let hay = "What do 1865-04-14, 1881-07-02, 1901-09-06 and 1963-11-22 have in common?";
// 'm' is a 'Match', and 'as_str()' returns the matching part of the haystack.
let dates: Vec<&str> = re.find_iter(hay).map(|m| m.as_str()).collect();
assert_eq!(dates, vec![
"1865-04-14",
"1881-07-02",
"1901-09-06",
"1963-11-22",
]);
シンプルなキャプチャー
let re = Regex::new(r"Homer (.)\\. Simpson").unwrap();
let hay = "Homer J. Simpson";
let Some(caps) = re.captures(hay) else { return };
assert_eq!("J", &caps[1]);
caps[0] は全体(”Homer J. Simpson”)が入っている