用通配符代替 [英] Replace with wildcards
问题描述
我需要一些建议。假设我有以下字符串:阅读变量
我想找到这样的文本的所有作品中的字符串,并让所有的人都像下面这样:变量= MessageBox.Show
。因此,作为aditional的例子:
I need some advice. Suppose I have the following string: Read Variable
I want to find all pieces of text like this in a string and make all of them like the following:Variable = MessageBox.Show
. So as aditional examples:
"Read Dog" --> "Dog = MessageBox.Show"
"Read Cat" --> "Cat = MessageBox.Show"
你能帮助我吗?我需要在C#中使用正则表达式快速的建议。我认为这是一个涉及通配符的工作,但我不知道如何使用它们非常好......另外,我需要这个学校项目的明天...谢谢!
Can you help me? I need a fast advice using RegEx in C#. I think it is a job involving wildcards, but I do not know how to use them very well... Also, I need this for a school project tomorrow... Thanks!
编辑:这是我迄今所做的,它不工作: Regex.Replace(字符串,读,= Messagebox.Show)
。
This is what I have done so far and it does not work: Regex.Replace(String, "Read ", " = Messagebox.Show")
.
推荐答案
您可以做到这一点。
string ns= Regex.Replace(yourString,"Read\s+(.*?)(?:\s|$)","$1 = MessageBox.Show");
\s +
匹配1对多的空间字符
\s+
matches 1 to many space characters
(?: \s | $)(*?)
0匹配到的字符,直到第一空间(即 \s
),或直到字符串的结尾达到(即 $
)
(.*?)(?:\s|$)
matches 0 to many characters till the first space (i.e \s
) or till the end of the string is reached(i.e $
)
$ 1
表示第一个捕获组即(。*?)
$1
represents the first captured group i.e (.*?)
这篇关于用通配符代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!