2011-05-06 92 views
4

我有一个表达:需要用正则表达式帮助解析表达式

((((the&if)|sky)|where)&(end|finish)) 

我需要的是把符号和文字之间的空间,使得其结束了,如:

((((the & if) | sky) | where) & (end | finish)) 

正则表达式我想出了是(\w)*[(\&*)(\|*)]只得到我:

((((the& if) | sky) | where) & (end| finish))

我可以从居民的正则表达式大师那里得到一些帮助吗?我将在C#中使用它。

回答

2

编辑:由于您使用C#,试试这个:

output = Regex.Replace(input, @"([^\w\s]|\w(?!\w))(?!$)", "$1 "); 

这符合下列条件的任何字符后插入一个空格:

  • 是既不是字母,数字,下划线或空格
    • 或者是一个单词字符,不是跟着另一个单词字符
  • AND不在行尾。
2
resultString = Regex.Replace(subjectString, @"\b|(?<=\W)(?=\W)", " "); 

说明:

\b  # Match a position at the start or end of a word 
|  # or... 
(?<=\W) # a position between two 
(?=\W) # non-word characters 

(和替换那些具有空间)。

+0

我发现这个网站在开发和测试正则表达式模式有所帮助:HTTP://www.myregextester .com/index.php – ShaneBlake 2011-05-06 21:15:37

+1

这将导致类似'hello world'的信息被转换为'hello world'(3个空格)。不过,我不确定这是否是个问题。 – 2011-05-06 21:17:27

1

你可能只是每个单词后面添加一个空格,每个非字字符后(所以找\W|\w+,并与比赛和一个空格替换它如Vim中:

:s/\W\|\w\+/\0 /g 
1

你可以使用:

(\w+|&|\(|\)|\|)(?!$) 

这意味着一个字,或&符号或(符号或)符号或符号|之后不是字符串的端部;然后替换用火柴的匹配+空格符号。通过使用C#可以这样做,如:

var result = Regex.Replace(
       @"((((the&if)|sky)|where)&(end|finish))", 
       @"(\w+|&|\(|\)|\|)(?!$)", 
       "$+ " 
      ); 

现在result变量包含的值:

((((the & if) | sky) | where) & (end | finish))