如何检查和替换字符串值 [英] How to check and replace string values

查看:71
本文介绍了如何检查和替换字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想要实现的是我有一个字符串



string text = 其中name ='nilesh'或lastname ='nilesh'或distance ='nilesh'或gender ='nilesh';



来自此我想查看是否字符串中的距离是可用的,如果它可用,我实际上想检查他的值是否为数字,所以我想检查距离值是否为数字,并根据我要删除距离='nilesh',如果不是数字如果是的话我想继续保持原样



请建议

Hi ,

What i want to achieve is I have a string

string text = "where name='nilesh' or lastname='nilesh' or distance='nilesh' or gender='nilesh'";

from this I want to check if distance is available in the string and if its available I actually want to check if his value is numeric or not , so I want to check distance value is numeric or not and based on that I want to remove distance='nilesh' if not numeric and if yes I want to keep as it is

please suggest

推荐答案

你可以尝试使用正则表达式,如果是匹配则用空字符串替换匹配。



像这样:

[更新]在表达式中添加'或者',以摆脱双重或者。

[UPDATE2]更新了正则表达式以匹配实际要求。

You can try to use a regular expression, and if it is a match you replace the match with an empty string.

Like this:
[UPDATE] Added 'or\s' to the expression, to get rid of double or's.
[UPDATE2] Updated the regex to match the actual requirement.
private static Regex expression = new Regex(@"or\s*distance=\s*'[a-z]+'", RegexOptions.IgnoreCase);



表达式基本上意味着您找到单词距离,然后是 = 然后'任何字母' 在引号内。

匹配将发生在字符串中的任何位置。

\ * *表示零个或多个空格


The expression basically means that you find the word distance followed by = and then 'any letter' within the quotes.
The match will occur in any place within the string.
\s* means zero or more white spaces

string s = @"where name='nilesh' or lastname='nilesh' or distance='nilesh' or gender='nilesh' where name = 'nilesh' or lastname = 'nilesh' or distance = '1' or gender = 'nilesh'";
string t = expression.Replace(s, "");



结果是


the result is

where name='nilesh' or lastname='nilesh' or gender='nilesh' where name = 'nilesh' or lastname = 'nilesh' or distance = '1' or gender = 'nilesh'





我不知道你是否使用数字值附近的引号,但它与功能无关。



使用正则表达式最好有一个可以测试表达式的工具。我使用这个, RegExTest [ ^ ],但也有其他工具。



要了解正则表达式,你可以使用本网站: http://www.regular-expressions.info/ [ ^ ]



I don't know if you use quotes around numeric values or not, but it doesn't matter for the functionality.

When working with regular expressions it is good to have tool where you can test the expressions. I use this one, RegExTest[^], but there are other tools out there as well.

To learn about regular expressions you can use this site: http://www.regular-expressions.info/[^]


这篇关于如何检查和替换字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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