簡體   English   中英

使用Java Regex刪除字符串開頭的給定字符序列的出現次數

[英]Remove occurrences of a given character sequence at the beginning of a string using Java Regex

我有一個字符串,以一個或多個序列"Re:" 這個"Re:"可以是任何組合,例如。 Re<any number of spaces>: , re: , re<any number of spaces>: , RE:RE<any number of spaces>:等。

字符串的示例序列: Re: Re : Re : re : RE: This is a Re: sample string.
我想定義一個java正則表達式,它將識別和去除所有出現的Re: ,但只有字符串開頭的那些而不是字符串中出現的那些。
因此輸出應該看起來像This is a Re: sample string.
這是我嘗試過的:

String REGEX = "^(Re*\\p{Z}*:?|re*\\p{Z}*:?|\\p{Z}Re*\\p{Z}*:?)";
String INPUT = title;
String REPLACE = "";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
while(m.find()){
  m.appendReplacement(sb,REPLACE);
}
m.appendTail(sb);

我正在使用p{Z}來匹配空格(在這個論壇的某處找到了這個,因為Java正則表達不能識別\\s )。

我在使用此代碼時遇到的問題是搜索在第一次匹配時停止,並轉義while循環。

嘗試這樣的替換語句:

yourString = yourString.replaceAll("(?i)^(\\s*re\\s*:\\s*)+", "");

正則表達式的解釋:

(?i)  make it case insensitive
^     anchor to start of string
(     start a group (this is the "re:")
\\s*  any amount of optional whitespace
re    "re"
\\s*  optional whitespace
:     ":"
\\s*  optional whitespace
)     end the group (the "re:" string)
+     one or more times

在你的正則表達式:

String regex = "^(Re*\\p{Z}*:?|re*\\p{Z}*:?|\\p{Z}Re*\\p{Z}*:?)"

這是它的作用:

正則表達圖像

看到它住在這里

它匹配字符串,如:

  • \\p{Z}Reee\\p{Z:
  • R\\p{Z}}}

這對你嘗試做的事情毫無意義:

你最好使用如下的正則表達式:

yourString.replaceAll("(?i)^(\\s*re\\s*:\\s*)+", "");

或者讓@Doorknob開心,這是使用Matcher實現這一目標的另一種方法:

Pattern p = Pattern.compile("(?i)^(\\s*re\\s*:\\s*)+");
Matcher m = p.matcher(yourString);
if (m.find())
    yourString = m.replaceAll("");

正如doc所說的那樣與yourString.replaceAll()完全相同)

正則表達圖像

在這里查找

(我和@ Doorknob有相同的正則表達式,但感謝@jlordo對於replaceAll和@Doorknob考慮(?i)不區分大小寫的部分;-))

暫無
暫無

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

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