简体   繁体   English

替换为Regexp无法正常工作

[英]Replace with Regexp not working

I want to replace a query string like this: 我想替换这样的查询字符串:

SELECT abc,def,ghi,jhk FROM table....

with

SELECT X FROM table....

this should be quite easy and i get the regexp replace to work as expected, but i cant get my expression right. 这应该很容易,而且我可以将regexp替换为预期的工作,但是我无法正确表达自己的意思。 This is what i have: 这就是我所拥有的:

rgx = new Regex("SELECT*.FROM");
data = rgx.Replace(data, "SELECT X FROM");

It also does not work in the online evaluator i tried, but i have no clue how it has to be then. 它在我尝试过的在线评估程序中也不起作用,但是我不知道当时的情况。 And how do i get a modifier in there? 以及如何在其中获得修饰符? I think it should be ungreedy. 我认为应该不满意。

I know that this whole thing might seem useless but this is exactly what i want and need to do. 我知道这件事似乎没用,但这正是我想要和需要做的。

You mixed up the * and . 您将*和混合在一起.

Also you might want to add some spaces in there, otherwise the regex would also match SELECTFOOBARFROM . 另外,您可能想在其中添加一些空格,否则正则表达式也将与SELECTFOOBARFROM匹配。

Further more (assuming that C#'s Regexes support non-greediness) I'd make the wildcard non-greedy via a trailing ? 再进一步(假设C#的正则表达式支持非贪婪性),我会通过尾部使通配符成为非贪婪的? .
Right now your regex is greedy. 现在,您的正则表达式很贪婪。 As a result your current regex would change this: 结果,您当前的正则表达式将更改此:

SELECT Foo FROM Bar WHERE Baz IN (SELECT FooID FROM Bar WHERE Foo = 'Foo')

into this: 到这个:

SELECT X FROM Bar WHERE Foo = 'Foo')

while the correct result would have been this: 而正确的结果应该是这样的:

SELECT X FROM Bar WHERE Baz IN (SELECT X FROM Bar WHERE Foo = 'Foo')

Ergo, go with this instead: 嗯,改用这个:

rgx = new Regex("SELECT .*? FROM");

You want: 你要:

rgx = new Regex("SELECT.*FROM");

Note the order of the . 请注意的顺序。 and the *. 和*。

the * is basically a modifier for whatever character or group it follows so in yours you were matching 0 or more of the letter T instead of 0 or more of any character. *基本上是它后面跟随的任何字符或组的修饰符,因此在您的字符或组中,您匹配的是字母T的0或更多,而不是任何字符的0或更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM