2017-10-03 2 views
0

で区切られた文字列を抽出する:私は現在、何正規表現は、文字列からトークン

["@user", "do foo, and bar please, #urgent", "contact xyz"] 

"@user do foo, and bar please, #urgent. contact xyz" 

が、私は3つの文字列のこの配列を抽出する必要が私だけでindexOf()トークン"@"" "". "との間に部分文字列を取得します。

RegExで最適化したいと思います。配列内のようにいくつかのトークンを検索してグループ化するにはどうすればよいですか?

+1

'indexOf()'は実際には正規表現よりも安価な演算であるかもしれません。しかし、正規表現でもそれほど難しくありません。おそらく、特定の文字にトークンとして注目する必要はありません。 https://regex101.com/r/tKuM77/6 – CAustin

答えて

0

あなたがこれを行うことができます:

List<string> output = new List<string>(); 
string input = "@user do foo, and bar please, #urgent. contact xyz"; 
string pattern = @"(@[\w]+)"; // inclusive split, @User will be included in the split result 
string[] regexSplit = Regex.Split(input, pattern); 

foreach (string str in regexSplit) 
{ 
    // exclusive split, . won't be included in split result 
    string[] res = str.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); 
    output.AddRange(res); 
} 

ご注意: を(+ [\ W] @)任意の英数字の文字 を意味ワット\:一つ以上の英数字の文字が続く記号@を意味し、我々はそれらを置きますそれは包含的な分割になるでしょう。