2014-11-04 99 views
0

我想写一个正则表达式代码来删除空格,第一个单词,括号和所有数字。删除正则表达式中的空格

我有以下文字:

{a, 1, b, 4, c, 6, d, 8} 

我感兴趣的是:b,c和d,而排除。

这个正则表达式:"\,([^{^,+^\d-}]*)"给了我b,c和d,但有空格。

我试过这个:"\,([^{^,+^\d-^\s+}]*)"但没有运气。

有没有提示?

+0

您正在使用什么语言/工具? – 2014-11-04 21:51:55

+1

你想要做什么语言?因为修剪'{}'和分割'''会容易得多。 – Marty 2014-11-04 21:52:17

+0

语言工具是C# – user4214837 2014-11-04 21:53:38

回答

2

在你的情况,最简单的解决办法是,提取所有的字母,而忽略了第一场比赛:

var matches = Regex.Matches(inputText, @"\p{L}+") 
        .Cast<Match>() 
        .Skip(1) 
        .Select(match => match.Value) 
        .ToList(); 

也就是说,如果你不需要验证输入字符串格式。如果你这样做,你可以使用事先以下模式:

^\{(?:(?:\s*\w+\s*,\s)*\s*\w+)?\s*\}$ 

这意味着:

^\{      # Opening brace 
    (?:     # Optionally: 
    (?:\s*\w+\s*,\s)* # Words followed by commas 0 to n times 
    \s*\w+    # Followed by a word 
)?      
\s*      # Optional whitespace 
\}$      # Closing brace 

Demo of the validation regex

相关问题