Skip to content

Instantly share code, notes, and snippets.

@bragnikita
Created January 11, 2017 08:44
Java regular expressions API demo
public class RegexpHint {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("title", "Oriko"); map.put("volume", "01"); map.put("chapter", "4");
String input = "Title: $title; volume: $volume; chapter $chapter; ready";
String regex = "\\$(\\w+)";
Matcher m = Pattern.compile(regex).matcher(input);
m.region(7,13);
System.out.println(m.matches()); //интервал $title полнстью совпадает
m.region(7,14);
System.out.println(m.lookingAt()); //интервал $title; совпадает в начале
m.reset(); //сброс состояния
StringBuffer result = new StringBuffer();
while (m.find()) {
m.appendReplacement(result, map.get(m.group(1)));
}
m.appendTail(result);
System.out.println(result);
// \Q[]*fewfw\f\w{fw!\E
System.out.println(Pattern.quote("[]*fewfw\\f\\w{fw!"));
// \\2 \$2 \$\$ \$
System.out.println(Matcher.quoteReplacement("\\2 $2 $$ $"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment