我正在嘗試使用 Java 中的正則運算式從以下字串中捕獲資料:
SettingName = "Value1",0x2,3,"Value4 contains spaces", "Value5 has a space before the string that is ignored"
字串前面可以有任意數量的空格,可以忽略。它還可能包含比此處列出的更多或更少的值,這只是一個示例。
我的目的是捕捉這些群體:
我嘗試使用的正則運算式是:
\s*([\w\/.-] )\s*=(?:\s*(\"?[^\",]*\"?)(?:,|\s*$))
\s* -> Consume an arbitrary number of whitespace
( -> Start a capturing group (group 1)
[\w\/.-] -> Get a letter of the SettingName, which may be contain alphanumberic, /, ., and -
-> Get the previous token one or more times (so group 1 is not blank)
) -> End the capturing group
\s* -> Consume an arbitrary amount of whitespace
= -> Consume the equals sign
(?: -> Start an uncaptured group
\s* -> Consume an arbitrary amount of whitespace
( -> Start a captured group
\"? -> Consume a quote, if it exists
[^\",] -> Consume any nonquote, noncomma character
\"? -> Consume the end quote, if it exists
) -> End the captured group
(?: -> start a uncaptured group
,|\s*$ -> capture either a comma or end of line (string?) character
) -> end the uncaptured group
) -> end the outer uncaptured group
-> match the outer uncaptured group 1 or more times
我正在使用此代碼:
private static final String regex = "\\s*([\\w\\/.-] )\\s*=(?:\\s*(\"?[^\",]*\"?)(?:,|\\s*$)) ";
private static final Pattern settingPat = Pattern.compile(regex);
...
public String text;
public Matcher m;
...
public void someMethod(String lineContents)
{
m = settingPat.matcher(text);
if(!m.matches())
... (do other stuff)
else
{
name = m.group(1); // should be "SettingName"
value[0] = m.group(2); // should be "\"Value1\""
value[1] = m.group(3); // should be "0x2"
...
}
}
使用此代碼,它與字串匹配,但似乎我只捕獲了最后一組。Java 和/或正則運算式是否支持使用 修飾符重復任意捕獲組?
uj5u.com熱心網友回復:
您只有 2 個捕獲組,因此在結果中不能獲得超過 2 個組。你將不得不運行一個回圈來匹配所有的重復
您可以在while回圈中使用此正則運算式來獲取所有匹配項:
(?:([\w/.-] )\h*=|(?!^)\G,)\h*((\"?)[^\",]*\3)
\G斷言位置在前一個匹配的末尾或第一個匹配的字串的開頭,因為我們使用(?!^)我們強制\G只匹配前一個匹配末尾的位置
正則運算式演示
代碼演示
代碼:
final String regex = "(?:([\\w/.-] )\\h*=|(?!^)\\G,)\\h*((\"?)[^\",]*\\3)";
final String string = "SettingName = \"Value1\",0x2,3,\"Value4 contains spaces\", \"Value5 has a space before the string that is ignored\"";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
if (matcher.group(1) != null)
System.out.println(matcher.group(1));
System.out.println("\t=> " matcher.group(2));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377511.html
