Skip to content

Instantly share code, notes, and snippets.

@blacknon
Created February 9, 2022 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacknon/832152319f8124f928a2c65736767c77 to your computer and use it in GitHub Desktop.
Save blacknon/832152319f8124f928a2c65736767c77 to your computer and use it in GitHub Desktop.
regexでmatchした箇所をハイライト表示させるためのサンプルコード(rust版)
extern crate regex;
use regex::Regex; // 1.1.8
fn main() {
let seperator = Regex::new(r"is a").unwrap();
let splits: Vec<_> = seperator.split("this... is a, test").into_iter().collect();
for split in splits {
println!("\"{}\"", split);
}
// let cap = seperator.captures("this... is a, test");
// println!("{}", cap.);
let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
let caps = re.captures("abc123").unwrap();
let text1 = caps.get(1).map_or("", |m| m.as_str());
let text2 = caps.get(2).map_or("", |m| m.as_str());
let text3 = caps.get(3).map_or("", |m| m.as_str());
println!("text1: {}", text1);
println!("text2: {}", text2);
println!("text3: {}", text3);
let pattern = Regex::new(r"rot").unwrap();
let s = "swap drop rot number(3) \"item list\" xget 'item count'";
let matches: Vec<String> = pattern
.find_iter(s)
.map(|m| m.as_str().to_string())
.collect();
println!("Matches: {}\n - {}", matches.len(), matches.join("\n - "));
let mut text = "".to_string();
let mut last_match: usize = 0;
for m in pattern.find_iter(s) {
let start: usize = m.start();
let end: usize = m.end();
let before_range_text = &s[last_match..start];
let range_text = &s[start..end];
text += before_range_text;
text += &"____".to_string();
text += range_text;
text += &"____".to_string();
last_match = end;
}
text += &s[last_match..];
println!("text: {}", text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment