C# 字符串不在正则表达式中
我想使用正则表达式在字符串中查找匹配项。还有其他方法可以找到我正在寻找的模式,但我对Regex解决方案感兴趣 整理这些字符串C# 字符串不在正则表达式中,c#,regex,C#,Regex,我想使用正则表达式在字符串中查找匹配项。还有其他方法可以找到我正在寻找的模式,但我对Regex解决方案感兴趣 整理这些字符串 "ABC123" "ABC245" "ABC435" "ABC Oh say can You see" 我想匹配查找“ABC”后接“123”以外的任何内容。什么是正确的正则表达式 如果您觉得这更容易使用,它是regex的替代品。只是一个建议 List<string> strs = new List<string>() { "ABC123",
"ABC123"
"ABC245"
"ABC435"
"ABC Oh say can You see"
我想匹配查找“ABC”后接“123”以外的任何内容。什么是正确的正则表达式 如果您觉得这更容易使用,它是regex的替代品。只是一个建议
List<string> strs = new List<string>() { "ABC123",
"ABC245",
"ABC435",
"NOTABC",
"ABC Oh say can You see"
};
for (int i = 0; i < strs.Count; i++)
{
//Set the current string variable
string str = strs[i];
//Get the index of "ABC"
int index = str.IndexOf("ABC");
//Do you want to remove if ABC doesn't exist?
if (index == -1)
continue;
//Set the index to be the next character from ABC
index += 3;
//If the index is within the length with 3 extra characters (123)
if (index <= str.Length && (index + 3) <= str.Length)
if (str.Substring(index, 3) == "123")
strs.RemoveAt(i);
}
List strs=new List(){“ABC123”,
“ABC245”,
“ABC435”,
“NOTABC”,
“哦,你能看见吗?”
};
对于(int i=0;i 如果(索引请尝试以下测试代码。这应该满足您的要求
string s1 = "ABC123";
string s2 = "we ABC123 weew";
string s3 = "ABC435";
string s4 = "Can ABC Oh say can You see";
List<string> list = new List<string>() { s1, s2, s3, s4 };
Regex regex = new Regex(@".*(?<=.*ABC(?!.*123.*)).*");
Match m = null;
foreach (string s in list)
{
m = regex.Match(s);
if (m != null)
Console.WriteLine(m.ToString());
}
这使用了两种方法
我希望这能有所帮助。使用:
您可以使用以下选项检查字符串str
中是否存在匹配项:
Regex.IsMatch(str, "ABC(?!123)")
完整示例:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] strings = {
"ABC123",
"ABC245",
"ABC435",
"ABC Oh say can You see"
};
string pattern = "ABC(?!123)";
foreach (string str in strings)
{
Console.WriteLine(
"\"{0}\" {1} match.",
str, Regex.IsMatch(str, pattern) ? "does" : "does not"
);
}
}
}
唉,我上面的正则表达式将匹配ABC
,只要它后面不跟123
。如果您需要在ABC
之后至少匹配一个字符,而该字符不是123
(即,不匹配ABC
本身/字符串末尾),您可以使用ABC(?!123).
,点确保您在ABC
之后至少匹配一个字符:
我相信第一个正则表达式就是你想要的(只要“nothing”可以被视为“anything”:p
)。至于你的正则表达式问题,否定的前瞻/ABC(?!123)/
你的字符串总是以“ABC”开头吗?@Habib:不。它可以放在任何地方。你想在比赛中只看ABC,还是看它后面的东西?如果你也想看它后面的东西,你如何定义边界?你必须使用正则表达式吗?虽然它们很有效,但最好使用你更容易理解的代码。我发现正则表达式很难阅读,尽管我很难理解如果你得到一个正确的字符串,它会很有用。对不起,我只对正则表达式解决方案感兴趣。编辑这个问题是为了强调这一点。这太复杂了。正如Fabricio在他的文章中所说,你所需要的是/ABC(?!123)/
。
Regex.IsMatch(str, "ABC(?!123)")
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] strings = {
"ABC123",
"ABC245",
"ABC435",
"ABC Oh say can You see"
};
string pattern = "ABC(?!123)";
foreach (string str in strings)
{
Console.WriteLine(
"\"{0}\" {1} match.",
str, Regex.IsMatch(str, pattern) ? "does" : "does not"
);
}
}
}