gpt4 book ai didi

c# - 在具有特定条件的字符串中搜索子字符串

转载 作者:行者123 更新时间:2023-11-30 20:27:59 24 4
gpt4 key购买 nike

我想弄清楚,什么是在其他字符串中搜索子字符串以获得内容示例的相等输出的正确方法:

hello how are you

输入为真:

hey hello how are you ok
how are you
are you

错误的是:

you
how you are ok you
howareyou
howok
how you
hey hello

我想要一个字符串中包含的相同短语或部分短语为真,但不是单个单词或另一个序列中的单词。这样对于所有 (aList.Any(input.Contains)) 都是真的,对于所有 (aList.Contains(input)) 都是假的:

        List<string> aList = new List<string>() {
"hey hello how are you ok",
"how are you",
"are you",
"you",
"how you are ok you",
"howareyou",
"howok",
"how you",
"hey hello" };

string input = "hello how are you";

foreach (string a in aList)
{
if (a.Any(input.Contains))
{
Console.WriteLine(a + " - true");
}
else
{
Console.WriteLine(a + " - false");
}
}

Console.WriteLine("__\n\r");

foreach (string a in aList)
{
if (a.Contains(input))
{
Console.WriteLine(a + " - true");
}
else
{
Console.WriteLine(a + " - false");
}
}

最佳答案

我想到了这个解决方案:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{
List<string> aList = new List<string>()
{"hey hello how are you ok", "how are you", "are you", "you", "how you are ok you", "howareyou", "howok", "how you", "hey hello"};


var input = "hello how are you";

// build matcher
string[] chunks = input.Split(' ');
string matcher = "";
for (int i = chunks.Length, j = 0; i > 1; i--, j++){
var matcherPart = new string [i];
Array.Copy(chunks, j, matcherPart, 0, i);
matcher += "("+String.Join(@"+\s+", matcherPart) + ")";
}
matcher = matcher.Replace(")(", ")|(");

// Console.WriteLine(matcher);
//(hello+\s+how+\s+are+\s+you)|(how+\s+are+\s+you)|(are+\s+you)";


foreach (string a in aList)
{
Regex r = new Regex(matcher, RegexOptions.IgnoreCase);
Match m = r.Match(a);
Group g = m.Groups[0];
Console.WriteLine(a + " - " + (g.Captures.Count > 0));
}

/*

hey hello how are you ok - True
how are you - True
are you - True
you - False
how you are ok you - False
howareyou - False
howok - False
how you - False
hey hello - False

*/
}
}

构建匹配器部分使用可能的组合创建正则表达式,即此字符串 a b c d 正在转换为:(a+b+c+d)|(b+c+d) |(c+d)。有了它,您可以轻松地遍历列表值并应用正则表达式。 g.Captures.Count 告诉您列表项是否与您的模式匹配。

关于c# - 在具有特定条件的字符串中搜索子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48009998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com