gpt4 book ai didi

java - 带逗号的正则表达式模式java

转载 作者:行者123 更新时间:2023-11-30 02:53:51 24 4
gpt4 key购买 nike

我有一个来自 Excel 列的以下字符串

  "\"USE CODE \"\"Gef, sdf\"\" FROM 1/7/07\""

我想设置正则表达式模式来检索整个字符串,以便我的结果完全相同

"USE CODE ""Gef, sdf"" FROM 1/7/07"

以下是我尝试过的

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
public static void main( String args[] ){

// String to be scanned to find the pattern.
String line = "\"USE CODE \"\"Gef, sdf\"\" FROM 1/7/07\", Delete , Hello , How are you ? , ";
String line2 = "Test asda ds asd, tesat2 . test3";

String dpattern = "(\"[^\"]*\")(?:,(\"[^\"]*\"))*,|([^,]+),";
// Create a Pattern object
Pattern d = Pattern.compile(dpattern);
Matcher md = d.matcher(line2);

Pattern r = Pattern.compile(dpattern);

// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: 0 " + m.group(0) );
// System.out.println("Found value: 1 " + m.group(1) );
//System.out.println("Found value: 2 " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}

其结果在,(逗号)之后中断,因此输出为

Found value: 0 "USE CODE ""Gef,

应该是

Found value: 0 "USE CODE ""Gef sdf"" FROM 1/7/07",

对于第二行Matcher m = r.matcher(line2);输出应该是

Found value: 0 "Test asda ds asd",

最佳答案

您可以使用

(?:"[^"]*(?:""[^"]*)*"|[^,])+

请参阅regex demo

说明:

  • " - 前导引号
  • [^"]* - 除双引号外的 0+ 个字符
  • (?:""[^"]*)* - 0+ 个 "" 文本序列,后跟 0+ 个字符(双引号除外)<
  • " - 尾随引号

或者:

  • [^,] - 除逗号之外的任何字符

整个模式匹配 1 次或多次,因为它被 (?:...)+ 括起来,并且 + 匹配 1 次或多次出现。

IDEONE demo :

String line = "\"USE CODE \"\"Gef, sdf\"\" FROM 1/7/07\", Delete , Hello , How are you ? , ";
String line2 = "Test asda ds asd, tesat2 . test3";
Pattern pattern = Pattern.compile("(?:\"[^\"]*(?:\"\"[^\"]*)*\"|[^,])+");
Matcher matcher = pattern.matcher(line);
if (matcher.find()){ // if is used to get the 1st match only
System.out.println(matcher.group(0));
}
Matcher matcher2 = pattern.matcher(line2);
if (matcher2.find()){
System.out.println(matcher2.group(0));
}

关于java - 带逗号的正则表达式模式java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37829717/

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