[英]Regex pattern java with commas
我有一個來自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",
您可以使用
(?:"[^"]*(?:""[^"]*)*"|[^,])+
說明 :
"
-前導報價 [^"]*
-除雙引號外的0+個字符 (?:""[^"]*)*
-0 +個""
文本序列,后跟0 +字符(雙引號除外) "
-尾隨報價 要么:
[^,]
-除逗號以外的任何字符 整個模式被匹配1次或多次,因為它用(?:...)+
括起來,而+
匹配1次或多次。
IDEONE演示 :
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.