java - 如何使用正则表达式解析字符串

标签 java regex string

我是 java 的新手,正在尝试找到一种更好的方法。可能使用正则表达式。

String text = test.get(i).toString()
// text looks like this in string form:
// EnumOption[enumId=test,id=machine]

String checker = text.replace("[","").replace("]","").split(",")[1].split("=")[1];

// checker becomes machine

我的目标是解析 text 字符串并返回 machine。这就是我在上面的代码中所做的。

但这看起来很难看。我想知道这里可以使用什么样的正则表达式来使它变得更好一点?或者其他建议?

最佳答案

使用正则表达式的后视:

(?<=\bid=)[^],]*

See Regex101 .

(?<=     )            // Start matching only after what matches inside
    \bid=             // Match "\bid=" (= word boundary then "id="),
          [^],]*      // Match and keep the longest sequence without any ']' or ','

在 Java 中,像这样使用它:

import java.util.regex.*;

class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("(?<=\\bid=)[^],]*");
    Matcher matcher = pattern.matcher("EnumOption[enumId=test,id=machine]");
    if (matcher.find()) {
      System.out.println(matcher.group(0));
    }
  }
}

这导致

machine

关于java - 如何使用正则表达式解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65293381/

相关文章:

java - android递归分割字符串异常

iOS 将字符串传递给另一个应用程序

c - 反转字符串时获取 "Segmentation fault Core Dumped Error "

java - 如何使用 RestEasy 验证冗余查询参数?

java - 消化 md5 抛出 UTF8 错误 - Java

Python 特殊字符转义

java - 通过分割或使用正则表达式将 ID 与另一个字符串进行匹配

java - 使用 showMessageDialog 显示数组并返回选定的值

Java泛型无法将类型转换为类型

node.js - 使用 node.js 清理来自 stdin 的流