簡體   English   中英

正則表達式,用於匹配變量和逗號之間的空格

[英]RegEx for matching spaces between a variable and commas

我正在嘗試通過url字符串進行解析,以便可以對其進行驗證以進行測試。 我的弦看起來

p_videoid=119110,p_videoepnumber= 0,p_videoairdate=NOT NULL,videoseason=null

我的問題是某些視頻在p_videoepnumber = 0中有一個空格。我需要找到以p_videoepnumber開頭並以逗號結尾的子字符串,然后刪除所有空格。

我希望最終輸出看起來像:

p_videoid=119110,p_videoepnumber=0,p_videoairdate=NOTNULL,videoseason=null

我不能只從字符串中刪除所有空格,因為某些值帶有空格。

根據您的發言,您可以簡單地執行以下操作:

string.replace("= ","=");

如果只希望更改p_videoepnumber鍵:

string.replace("p_videoepnumber= ","p_videoepnumber=");
// Using regex:
string.replaceAll("(p_videoepnumber=)(\\s+)","$1");

演示

因此,在此String中:

p_videoid=119110,p_videoepnumber= 0,p_videoairdate=NOT NULL,videoseason=null

您想捕獲p_videoepnumber= 0,

我想到的第一個想法是嘗試匹配p_videoepnumber= .*, ,但實際上它會捕獲p_videoepnumber= 0,p_videoairdate=NOT NULL,

當您想停在第一個逗號時,實際上將使用一個勉強的匹配器。 您實際上將匹配p_videoepnumber= .*?, (注意多余的? )。

從這一點來看,這是注釋的代碼:

String req = "p_videoid=119110,p_videoepnumber= 0,p_videoairdate=NOT NULL,videoseason=null";

// Add parenthesis to indicate the group to capture
String regex = "(p_videoepnumber= .*?,)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(req);

// find() finds the next subsequence of the input sequence that matches the pattern.
if (matcher.find()) {
    // Displays the number of found groups : 1
    System.out.println(matcher.groupCount());
    // Displays the found group : p_videoepnumber= 0,
    System.out.println(matcher.group(1));
    // Replace " " with "" in the first group and display the result : 
    // p_videoid=119110,p_videoepnumber=0,p_videoairdate=NOT NULL,videoseason=null
    System.out.println(matcher.replaceFirst(matcher.group(1).replaceAll(" ", "")));
} else {
    System.out.println("No match");
}

您可以使用String.split方法:

String[] splitedString = "yourString".split(",");

然后您可以迭代String數組的每個元素,並找到以p_videoepnumber開頭的元素

for(int i=0; i<splitedString.length; i++){
    if(splitedString[i].startsWith("p_videoepnumber"){
        splitedString[i] = splitedString[i].trim();
     }
}
String parsedString = String.join(",", splitedString);

此RegEx可能會幫助您這樣做。 它只是在兩個可能存在空格的邊界之間創建一個組:

p_videoepnumber=(\s+)[0-9]+,
  • 您可以簡單地用$1調用這些空格,並將其替換為空字符串''

  • 如果願意,還可以在此表達式中添加其他邊界。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM