gpt4 book ai didi

java - 提取逗号之间不带引号的值

转载 作者:行者123 更新时间:2023-12-02 02:12:19 24 4
gpt4 key购买 nike

假设我有一个字符串,例如 'John','Smith' 。我希望我的正则表达式提取值 JohnSmith来自该字符串,不带逗号和引号。我环顾网站,找到了一个解决方案,可以去掉逗号,但不能去掉引号。

这是我尝试过的正则表达式(?:^|(?<=,))[^,]*

这样我就得到了 'John''Smith' 。当然,我可以简单地迭代 Matcher像这样并手动删除引号,但我想知道是否有更直接的使用正则表达式的解决方案,而不必求助于 replaceAll .

Pattern pat = Pattern.compile("(?:^|(?<=,))[^,]*");
Matcher matcher = pat.matcher("'John', 'Smith'");
List<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group().replaceAll("'", ""));
}

最佳答案

以下正则表达式将起作用:“[^,']+”

以下是更新后的代码。

public static void main(String[] args) {
String regex = "[^,']+";
Pattern pat = Pattern.compile(regex);
Matcher matcher = pat.matcher("'John', 'Smith'");
List<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
System.out.println(matches);
}

输出:

[John,  , Smith]

关于java - 提取逗号之间不带引号的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49827725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com