Skip to content

Instantly share code, notes, and snippets.

@nuzayats
Created February 10, 2015 13:03
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 nuzayats/d978fec2306e098fc5ae to your computer and use it in GitHub Desktop.
Save nuzayats/d978fec2306e098fc5ae to your computer and use it in GitHub Desktop.
package converter;
import org.junit.Assert;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexpTest {
String input = "<li><a href=\"../../jbatch/hello/\" >anchor</a></li>";
String expected = "<li><a href=\"/entry/articles-jbatch-hello\" >anchor</a></li>";
@Test
public void numberedGroups() {
Pattern p = Pattern.compile("(<a href=\")\\.\\./\\.\\./(.*)/(.*)/\"");
Matcher matcher = p.matcher(input);
String result = matcher.replaceAll("$1/entry/articles-$2-$3\"");
Assert.assertEquals(expected, result);
}
@Test
public void namedGroups() {
Pattern p = Pattern.compile("(?<prefix><a href=\")\\.\\./\\.\\./(?<category>.*)/(?<handle>.*)/\"");
Matcher matcher = p.matcher(input);
String result = matcher.replaceAll("${prefix}/entry/articles-${category}-${handle}\"");
Assert.assertEquals(expected, result);
}
@Test
public void appendReplacement() {
Pattern p = Pattern.compile("(?<prefix><a href=\")(?<url>.*)\"");
Matcher matcher = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
// any complex logic can be placed here
String url = matcher.group("url");
String[] urls = url.split("/");
matcher.appendReplacement(sb, "${prefix}/entry/articles-" + urls[2] + "-" + urls[3] + "\"");
}
matcher.appendTail(sb);
String result = sb.toString();
Assert.assertEquals(expected, result);
}
@Test
public void escapeSpecialChars() {
String input = "../../jbatch/hello/";
String expected = "../../$1/${name}/";
Pattern p = Pattern.compile("(?<prefix>\\.\\./\\.\\.)/.*/.*/");
String result = p.matcher(input).replaceAll("${prefix}/" + Matcher.quoteReplacement("$1/${name}") + "/");
Assert.assertEquals(expected, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment