簡體   English   中英

使用正則表達式忽略Java中的模式

[英]Using Regex to ignore a pattern in java

我有一句話: "we:PR show:V" 我想使用正則表達式模式匹配器僅匹配":""\\\\s"之前的那些字符。 我使用以下模式:

Pattern pattern=Pattern.compile("^(?!.*[\\w\\d\\:]).*$");

但這沒有用。 獲得輸出的最佳模式是什么?

對於這種情況,如果您使用的是Java,則使用子字符串執行操作可能會更容易:

String input = "we:PR show:V";
String colon = ":";
String space = " ";
List<String> results = new ArrayList<String>();
int spaceLocation = -1;
int colonLocation = input.indexOf(colon);
while (colonLocation != -1) {
    spaceLocation = input.indexOf(space);
    spaceLocation = (spaceLocation == -1 ? input.size() : spaceLocation);
    results.add(input.substring(colonLocation+1,spaceLocation);

    if(spaceLocation != input.size()) {
        input = input.substring(spaceLocation+1, input.size());
    } else {
        input = new String(); //reached the end of the string
    }
}
return results;

這比嘗試在正則表達式上匹配要快。

以下正則表達式假定冒號后面的任何非空白字符(依次是非冒號字符)都是有效的匹配項:

[^:]+:(\S+)(?:\s+|$)

使用方式如下:

String input = "we:PR show:V";
Pattern pattern = Pattern.compile("[^:]+:(\\S+)(?:\\s+|$)");
Matcher matcher = pattern.matcher(input);
int start = 0;
while (matcher.find(start)) {
    String match = matcher.group(1); // = "PR" then "V"
    // Do stuff with match
    start = matcher.end( );
}

模式匹配,順序為:

  1. 至少一個不是冒號的字符。
  2. 冒號。
  3. 至少是非空白字符(我們的匹配項)。
  4. 至少一個空格字符或輸入結尾。

只要正則表達式與字符串中的某項匹配(從索引start ,循環就會繼續,該索引始終會調整為指向當前匹配結束之后的。

暫無
暫無

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

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