可以使用正则表达式(['"])(.*?)\1来提取成对出现的双引号或单引号中间的内容。

这个正则表达式的含义是:

  • (['"]):匹配一个单引号或双引号,并将其作为第一个捕获组。
  • (.*?):非贪婪匹配任意字符,将其作为第二个捕获组。
  • \1:引用第一个捕获组中的内容,确保引号成对出现。

以下是一个示例代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String input = "This is a 'test' string with 'quoted' content.";
        String pattern = "(['\"])(.*?)\\1";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(input);

        while (m.find()) {
            System.out.println("Matched: " + m.group(2));
        }
    }
}

输出结果为:

Matched: test
Matched: quoted
``
java 利用正则表达式提取成对出现的双引号或单引号中间的内容不是成对的不提取

原文地址: http://www.cveoy.top/t/topic/ib1X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录