[英]Replace character with any possible string c#
Lets say i have string like this Test%Test
and i have stored strings like this: 可以说我有像这样的字符串Test%Test
,我存储了像这样的字符串:
Test123Test TestTTTTest Test153jhdsTest 123Test TEST123
So what i want is when i type in textbox Test
it would filter me everything with Test
in itselft and that will get me all strings which is easy, but i want to type in Test%Test
and it needs to filter me everything that has Test[anything]Test
in itself (so result would be first, second and third string). 所以我想要的是当我在文本框中输入Test
它会使用Test
int本身过滤所有内容,这将使我得到所有字符串,这很容易,但是我想输入Test%Test
,它需要过滤所有具有Test[anything]Test
本身Test[anything]Test
(因此结果将是第一个,第二个和第三个字符串)。 How can i do it? 我该怎么做?
a simple solution using a regex is: 使用正则表达式的简单解决方案是:
string[] values = new string[] { "Test123Test",
"TestTTTTest",
"Test153jhdsTest",
"123Test",
"TEST123" };
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
string[] filteredValues = values.Where(str => Regex.IsMatch(str, regex)).ToArray();
Or for a single match: 或单场比赛:
string value = "Test123Test";
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
if ( Regex.IsMatch(value, regex) )
{
// do something with the match...
}
We replace % with a regular expression (. = any character, * = zero or more times, ? = lazy quantifier). 我们用正则表达式替换%(。=任何字符,* =零次或多次,?=惰性量词)。 You can learn more about regular expressions here 您可以在此处了解有关正则表达式的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.