簡體   English   中英

使用包含逗號的正則表達式從字符串末尾刪除一系列字符

[英]Removing a sequence of characters from end of string using regex that contain a comma

我有以下數據:

I am BOB,FM testing
I am BOB,FM
I am BOB, FM
I am BOB    , FM
I am BOB , FM
BOB, FM I am
I am BOB , FM now

我只想從字符串末尾刪除序列“BOB,FM”。 (我們的逗號之間沒有空格。)

這將是正確的 output:

I am BOB,FM testing
I am
I am
I am
I am
BOB, FM I am
I am BOB , FM now

這就是我到目前為止還沒有工作的東西:

mystring = Regex.Replace(mystring, @"[BOB,FM]*$", string.Empty);

您可以在BOB之前和之后匹配可選的水平空白字符[\p{Zs}\t]*以及 FM 之間的逗號,而無需列出字符 class 中的字符。

要匹配空白字符,您可以使用\s*

[\p{Zs}\t]*\bBOB[\p{Zs}\t]*,[\p{Zs}\t]*FM$

在替換中使用空字符串。

正則表達式演示

您可以使用

var result = Regex.Replace(text, @"[\s-[\n]]*BOB[\s-[\n]]*,[\s-[\n]]*FM[\s-[\n]]*$", "", RegexOptions.Multiline);

請參閱正則表達式演示

其他可能的模式看起來像

@"[^\S\r\n]*BOB[^\S\r\n]*,[^\S\r\n]*FM[^\S\n]*$"
@"[\p{Zs}\t]*BOB[\p{Zs}\t]*,[\p{Zs}\t]*FM[\p{Zs}\t\r]*$"

詳情

  • [\s-[\n]]* - 零個或多個除 LF 之外的空白字符
  • BOB - BOB文本
  • [\s-[\n]]*,[\s-[\n]]* - a ,包含可選的零個或多個空格字符,而不是 LF
  • FM - FM字符串
  • [\s-[\n]]* - 零個或多個除 LF 之外的空白字符
  • $ - 行尾。

暫無
暫無

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

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