我是 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=)[^],]*
(?<= ) // 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/