編輯:這是一個更新的解決方案,解決您最近更新中的要點。這個想法是一樣的,除非你有一個子字符串,它需要在每個字符之間插入忽略模式。如果子字符串包含空格,它將在空格上分割並在這些字詞之間插入忽略模式。如果您不需要後者的功能(這更符合您的原始問題),那麼您可以刪除提供該模式的Split
和if
檢查。
請注意,這種方法不會是最有效的。
string input = @"foo ?A&3/3/C)412& bar A341C2";
string substring = "A41";
string[] ignoredChars = { "&", "/", "3", "C", ")" };
// builds up the ignored pattern and ensures a dash char is placed at the end to avoid unintended ranges
string ignoredPattern = String.Concat("[",
String.Join("", ignoredChars.Where(c => c != "-")
.Select(c => Regex.Escape(c)).ToArray()),
(ignoredChars.Contains("-") ? "-" : ""),
"]*?");
string[] substrings = substring.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string pattern = "";
if (substrings.Length > 1)
{
pattern = String.Join(ignoredPattern, substrings);
}
else
{
pattern = String.Join(ignoredPattern, substring.Select(c => c.ToString()).ToArray());
}
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine("Index: {0} -- Match: {1}", match.Index, match.Value);
}
嘗試這種解決方案出來:
string input = "Hello, -this- is a string";
string[] searchStrings = { "Hello", "this" };
string pattern = String.Join(@"\W+", searchStrings);
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
}
的\W+
將匹配任何非字母數字字符。如果您想自己指定它們,則可以將其替換爲要忽略的字符的字符類別,例如[ ,.-]+
(始終將短劃線字符放在開頭或結尾處以避免意外範圍指定)。另外,如果你需要的情況下被忽略使用RegexOptions.IgnoreCase
:
Regex.Matches(input, pattern, RegexOptions.IgnoreCase)
如果子是一個完整的字符串的形式,如「你好這個」,你可以很容易地進入了searchString
陣列形式這種方式:
string[] searchString = substring.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
@Fredy看看我更新的響應,如果我理解正確的,應該包括更新後的場景。 – 2010-04-07 16:14:45
@Fredy - 是否安全地斷定您希望輸入字符串和搜索字符串在搜索之前都乾淨不需要的字符?如果是這樣,下面我提供了一個使用RegEx和字符串搜索的解決方案。 – 2010-04-07 16:51:47
@Ahmad - 我喜歡你的更新,我會從那裏採取一些想法,謝謝。 – 2010-04-07 18:16:53