簡體   English   中英

在C#中按字符限制正則表達式

[英]Limit regex expression by character in c#

我得到以下模式(\\s\\w+)我需要用空格將字符串中的每個單詞匹配。

例如

當我有這個字符串

many word in the textarea must be happy

我懂了

 many     
 word    
 in    
 the    
 textarea    
 must    
 be    
 happy

是正確的,但是例如當我有另一個角色時

many word in the textarea , must be happy

我懂了

 many     
 word    
 in    
 the    
 textarea    
 must    
 be    
 happy

但是must be happy應該被忽略,因為我希望它在字符串中出現另一個字符時中斷

編輯:

例子2

all cats  { in } the world are nice

應該退貨

all
cats

因為{是我的另一個分隔符

例子3

My 3 cats are ... funny

應該退貨

My
3
cats
are

因為3是字母數字和. 是我的分隔符

我能做什么?

為此,您需要使用\\G定位符來匹配字符串開頭或最后匹配之后的位置。 因此您可以使用以下模式進行操作:

@"(?<=\G\s*)\w+"
[^\w\s\n].*$|(\w+\s+)

嘗試this.Grab的捕獲或matches.See demo.Set標志m為多行模式。

參見演示。

http://regex101.com/r/kP4pZ2/12

我認為我是Sam的評論是正確的:您將需要兩個正則表達式。

  1. 捕獲文本,直到一個非單詞字符為止。
  2. 捕獲所有單詞,並在一側留一個空格。

這是相應的代碼:

  1. "^(\\\\w+\\\\s+)+"
  2. "(\\\\w+\\\\s+)"

您可以將兩者結合起來,很容易地捕獲單個單詞-就像這樣

"^(\\\\w+\\\\s+)+"

這是演示該模式的完整代碼:

string input = "many word in the textarea , must be happy";

string pattern = "^(\\w+\\s+)+";

Match match = Regex.Match(input , pattern);

// Never returns a NullReferenceException because of GroupsCollection array indexer - check it out!
foreach(Capture capture in match.Groups[1].Captures)
{
    Console.WriteLine(capture.Value);
}

編輯

查看Casimir et Hippolyte,這是一個非常干凈的答案。

合計一個正則表達式:-)結果在list

Regex regex = new Regex(@"^((\w+)\s*)+([^\w\s]|$).*");

Match m = regex.Match(inputString);
if(m.Success)
{
    List<string> list = 
        m.Groups[2].Captures.Cast<Capture>().
        Select(c=>c.Value).ToList();
}

暫無
暫無

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

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