C#字符串替换为正则表达式 [英] C# string replace with regex

查看:157
本文介绍了C#字符串替换为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有文字FirstName ='Mahesh'和姓氏='Mohan',我想把字符串更改为

FirstName喜欢'%Mahesh%'和姓氏喜欢'%Mohan%'如何使用string.Replace



我拥有什么尝试过:



我骂了它idint得到任何解决方案

Hi,

I have text "FirstName = 'Mahesh' and Last Name ='Mohan'" , i want change the string to
"FirstName Like '%Mahesh%' and Last Name Like '%Mohan%'" how its possible using string.Replace

What I have tried:

I goolged it idint get any solution

推荐答案

唯一的原因是这是连接字符串以将其发送到SQL,这是一个非常非常糟糕的主意。您永远不应该连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。总是使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:

The only reason to do that is to concatenate a string to send it to SQL, and that's a very, very bad idea. You should never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

哪个SQL看作三个单独的命令:

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全有效的SELECT

A perfectly valid SELECT

DROP TABLE MyTable;

完全有效的删除表格通讯和

A perfectly valid "delete the table" command

--'

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。你经常定期备份,不是吗?



所以不同地构建你的整个字符串:

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

So build your whole string differently:

... WHERE FirstName LIKE '%' + @FN + '%' AND LastName LIKE '%' + @LN + '%'

并通过参数@FN传递Mahesh和Mohan部分@LN分别。

and pass the "Mahesh" and "Mohan" parts through via the parameters @FN and @LN respectively.


试试这个:

Try this:
string s = @"FirstName = 'Mahesh' and Last Name ='Mohan'";

//find ending [']
string find2 = @"\b\s?'";
string replacement2 = "%'";
Regex r = new Regex(find2);
s=r.Replace(s, replacement2);

//find [=']
string find1 = @"=\s?'\b";
string replacement1 = @" Like '%";
r = new Regex(find1);
s= r.Replace(s, replacement1);

Console.WriteLine(s);





详情请见:正则表达式中的替换| Microsoft Docs [ ^ ]


这篇关于C#字符串替换为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆