[英]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: 我想出的正则表达式是
(\\w)*[(\\&*)(\\|*)]
只能得到我:
( ( ( ( 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#.
我将在C#中使用它。
Edit: Since you're using C#, try this: 编辑:因为你正在使用C#,试试这个:
output = Regex.Replace(input, @"([^\w\s]|\w(?!\w))(?!$)", "$1 ");
That inserts a space after any character that matches the following conditions: 在符合以下条件的任何字符之后插入空格:
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). (并用空格替换)。
你可以在每个单词之后和每个非单词字符之后添加一个空格(所以寻找\\W|\\w+
并用匹配和空格替换它。例如在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:
通过使用c#,可以这样做:
var result = Regex.Replace(
@"((((the&if)|sky)|where)&(end|finish))",
@"(\w+|&|\(|\)|\|)(?!$)",
"$+ "
);
Now result
variable contains a value: 现在
result
变量包含一个值:
( ( ( ( the & if ) | sky ) | where ) & ( end | finish ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.