开发者

Need help with regex to parse expression

I have an expression:

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

What I need is to put a space between symbols and words so that it ends up like:

( ( ( ( the开发者_运维百科 & if ) | sky ) | where ) & ( end | finish ) )

The regex I came up with is (\w)*[(\&*)(\|*)] which only gets me:

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

Could I get a little help here from a resident regex guru please? I will be using this in C#.


Edit: Since you're using C#, try this:

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

That inserts a space after any character that matches the following conditions:

  • Is neither a letter, number, underscore, or whitespace
    • OR is a word character that is NOT followed by another word character
  • AND is not at the end of a line.


resultString = Regex.Replace(subjectString, @"\b|(?<=\W)(?=\W)", " ");

Explanation:

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

(and replace those with a space).


You could just add a space after each word and after each non-word character (so look for \W|\w+ and replace it with the match and a space. e.g. in Vim:

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


You could use:

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

which means a word, or a & symbol, or a ( symbol, or a ) symbol, or a | symbol not followed by an end of string; and then replace a match with a match + space symbol. By using c# this could be done like:

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

Now result variable contains a value:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜