使用LookAhead匹配以引号开始和结尾的字符串并剥离引号



我想匹配以同一报价开始和结尾的字符串,但仅以开始和结尾的引号:

"foo bar"
'foo bar'
"the quick brown fox"

,但我不希望这些匹配或剥离:

foo "bar"
foo 'bar'
'foo bar"
"the lazy" dogs

我尝试了此Java Regexp,但对所有情况都没有用:

Pattern.compile("^"|^'(.+)"$|'$").matcher(quotedString).replaceAll("");

我认为有一种方法可以做lookahead,但在这种情况下我不知道如何使用它。

或设置单独检查它们的IF语句会更有效?

Pattern startPattern = Pattern.compile("^"|^');
Pattern endPattern = Pattern.compile("$|'$");
if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) {
    ...
}

(当然,这与我不想要的'foo bar"匹配(

您正在寻找的正则是

^(["'])(.*)1$

替换字符串为 "$2"

Pattern pattern = Pattern.compile("^(["'])(.*)\1$");
String output = pattern.matcher(input).replaceAll("$2");

演示:https://ideone.com/3a5pet

这是一种可以检查您所有要求的方法:

public static boolean matches (final String str)
{
    boolean matches = false;
    // check for null string
    if (str == null) return false;
    if ((str.startsWith(""") && str.endsWith(""")) || 
        (str.startsWith("'") && str.endsWith("'")))
    {
        String strip = str.substring(1, str.length() - 1);
        // make sure the stripped string does not have a quote
        if (strip.indexOf(""") == -1 && strip.indexOf("'") == -1)
        {
            matches = true;
        }
    }
    return matches;
}

测试

public static void main(String[] args)
{
    System.out.println("Should Passn-----------");
    System.out.println(matches(""foo bar""));
    System.out.println(matches("'foo bar'"));
    System.out.println(matches(""the quick brown fox""));
    System.out.println("nShould Failn-----------");
    System.out.println(matches("foo "bar""));
    System.out.println(matches("foo 'bar'"));
    System.out.println(matches("'foo bar""));
    System.out.println(matches(""the lazy" dogs"));
}

输出

Should Pass
-----------
true
true
true
Should Fail
-----------
false
false
false
false

最新更新