如何在Java程序中找到转换为字符串的字符串?

基本上,我将Java程序作为字符串读入我的程序,并且我试图找到一种从中提取字符串的方法。我有一个循环遍历该程序的每个字符,这就是到达“'”时发生的情况。

else if (ch == '"')
            {
                String subString = " ";
                index ++;

                if (ch != '"')
                {
                    subString += ch;
                }

                else
                {
                    System.out.println(lineNumber + "," + TokenType.STRING + "," + subString);
                    index ++;
                    continue;
                }

不幸的是,这不起作用。 This is the way I am trying to output the subString.

本质上,我正在寻找一种方法将两个“ s”之间的所有字符加在一起以获得字符串。

sggxywcx 回答:如何在Java程序中找到转换为字符串的字符串?

您可以使用正则表达式:

Pattern regex = Pattern.compile("(?:(?!<')\"(.*?(?<!\\\\)(?:\\\\\\\\)*)\")");
Matcher m = regex.matcher(content);
while (m.find())
    System.out.println(m.group(1));

这将捕获带引号的字符串,并考虑转义的引号/反斜杠。

要分解模式:

  1. (?: ... ) =不作为一个组捕获(而是捕获内部)
  2. (?!<') =确保之前没有引号(避免使用“'”)
  3. \"( ... )\" =捕获引号内的内容
  4. .*? =匹配任何字符的最小字符串
  5. (?<!\\\\) =之前不匹配单反斜杠(double-escape =内容中的单反斜杠)
  6. (?\\\\\\\\)* =匹配0或偶数个反斜杠

5和6在引号之前只能匹配偶数个反斜杠。这样就可以使用字符串结尾,例如\\"\\\\",但不允许\"\\\",它们将成为字符串的一部分。

非正则表达式解决方案,还处理转义引号:

List<String> strings = new ArrayList<>();
int start = -1;
int backslashes = 0;
for (int i = 0; i < content.length(); i++) {
    char ch = content.charAt(i);
    if (ch == '"') {
        if (start == -1) {
            start = i + 1;
            backslashes = 0;
        } else if (backslashes % 2 == 1) {
            backslashes = 0;
        } else {
            strings.add(content.substring(start,i));
            start = -1;
        }
    } else if (ch == '\\') backslashes++;
}
strings.forEach(System.out::println);
本文链接:https://www.f2er.com/3032966.html

大家都在问