【问题标题】:How can I find a String within a Java program converted to a string?如何在转换为字符串的 Java 程序中找到字符串?
【发布时间】:2019-11-25 22:28:30
【问题描述】:

基本上,我将一个 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.

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

【问题讨论】:

  • 如果ch == '"' 为真,ch != '"' 永远不会为真。我不明白你为什么把一个嵌套在另一个里面。你的意思是在后续检查之前修改ch
  • 没错,更新 ch 不是索引
  • 我刚改成ch++还是不行。

标签: java substring


【解决方案1】:

你可以使用正则表达式:

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

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

分解模式:

  1. (?: ... ) = 不作为组捕获(内部被捕获)
  2. (?!&lt;') = 确保前面没有单引号(以避免'"')
  3. \"( ... )\" = 捕捉引号内的内容
  4. .*? = 匹配任意字符的最小字符串
  5. (?&lt;!\\\\) = 之前不匹配单个反斜杠(双转义 = 内容中的单个反斜杠)
  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);

【讨论】:

  • 有更简单的方法吗?我不熟悉正则表达式。
  • 我添加了一个非正则表达式解决方案。正则表达式绝对值得学习——在许多提取文本的情况下非常有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2013-06-28
  • 2016-04-21
  • 2011-03-25
  • 2023-03-17
  • 2012-06-25
相关资源
最近更新 更多