c#中的reg表达式——当我组合所有条件时很困难
我已经编写了上面的方法来获取匹配的模式字符串。我能单独理解所有模式匹配字符。但是当我把所有的条件放在一起的时候,我失败了。删除了我的测试模式数据,因为当我把所有条件放在一起时,我没有得到结果 以下是我正在寻找的模式c#中的reg表达式——当我组合所有条件时很困难,c#,C#,我已经编写了上面的方法来获取匹配的模式字符串。我能单独理解所有模式匹配字符。但是当我把所有的条件放在一起的时候,我失败了。删除了我的测试模式数据,因为当我把所有条件放在一起时,我没有得到结果 以下是我正在寻找的模式[stringData1-OnlyNumericData1-OnlyNumericData2]。stringData1的最大大小限制为10。stringData1、OnlyNumericData1和OnlyNumericData2中至少应有一个字符 案例 这是测试主题行[testDat
[stringData1-OnlyNumericData1-OnlyNumericData2]
。stringData1
的最大大小限制为10。stringData1
、OnlyNumericData1
和OnlyNumericData2
中至少应有一个字符
案例
[testData1-12345-678]
和test-1213-778]
。仅返回[testData1-12345-678]
,并且第二次出现时缺少[
[testData1-test12345-678Test]
和test-1213-778]
。由于OnlyNumericData1
和OnlyNumericData2
不是数字,因此不返回任何内容对您的整个问题执行的这个正则表达式测试只提供了2个匹配项:
public static string GetData(string subjectLine)
{
// Define the regular expression pattern.
string pattern = "";
string returnString = "Error";
Regex rgx = new Regex(pattern);
// Find matches.
MatchCollection matches = rgx.Matches(subjectLine);
if (matches.Count >= 1)
{
return matches[0].Value;
}
return returnString;
}
顺便说一句:这是一个在线dotnet regex测试的好网站我很幸运有这个网站:
string strRegex = @"\[\w{1,10}-[\d]+?-[\d]+\]";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"I have written the above method to get the matching pattern string. I understand individually all the pattern matching characters. But I am failing when I put all my conditions together. Removed my test pattern data since I am not getting the result when I put all my conditions together." + "\n\n" + @"Here is the pattern I am looking for [stringData1-OnlyNumericData1-OnlyNumericData2]. The max size limit for stringData1 is 10. At least one characters should be there in stringData1, OnlyNumericData1 and OnlyNumericData2." + "\n\n" + @"Cases" + "\n\n" + @"Here is the test subject line [testData1-12345-678] and test-1213-778]. Returns only [testData1-12345-678] and [ is missing in second occurrence." + "\n\n" + @"Here is the test subject line [testData1-test12345-678Test] and test-1213-778]. Returns nothing because OnlyNumericData1 & OnlyNumericData2 are not numeric.";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
public static string GetData(string subjectLine)
{
//im not sure if you want to include numeric in the stringData1 part
//replace [A-z\d] with [A-z] to accept only letters for stringData1
var result = Regex.Match(subjectLine, @"\[[A-z\d]{1,10}-\d+-\d+\]");
return result.Success ? result.Value : "Error";
}
如果“stringData1”包含破折号或右括号,该怎么办?“stringData1”不应包含破折号、右括号或左括号。如果包含此类数据,则视为坏数据,不应进行模式匹配。Mmmhm。那么,您用来过滤每个部分的模式是什么?
\A[\][\s\w-]{1,10}-[0-9]+-[0-9]+[\]]