
Problem: Match strings that contains a single quotation mark ('), but not multiple ones together.
Solution:
(?<!')'(?!')
This is a regex for a single quotation mark with a (?<!') in the left and a (?!’) in the right. The (?<!') is a ?< look behind if not ! a single quotation mark '. The (?!') is a look ahead ? if not ! a single quotation mark '.
Java code:
[java]import java.util.regex.Pattern;
public class RegexProblem {
public static void main(String args[]) {
Pattern single_quote = Pattern.compile("(?<!’)'(?!’)");
String[] phrases = {
"",
"’",
"a’a",
"aaa",
"aa’aa",
"aa”aa",
"aa”’aaa",
"aaa””aaa"
};
for(String phrase: phrases){
System.out.println(String.format("For %s is %s.", phrase,
single_quote.matcher(phrase).find()));
}
}
}
[/java]
The output is:
For is false. For ' is true. For a'a is true. For aaa is false. For aa'aa is true. For aa''aa is false. For aa'''aaa is false. For aaa''''aaa is false.