我需要匹配此字符串011Q-0SH3-936729
,而不是345376346
或asfsdfgsfsdf
它必须包含字符,数字和破折号
模式可以是011Q-0SH3-936729
或011Q-0SH3-936729-SDF3
或000-222-AAAA
或011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729-011Q-0SH3-936729
,我希望它能够匹配任何一个。原因是我真的不知道格式是否固定,而且我也找不到办法,因此我需要为具有任意破折号的模式提出一个通用解决方案,并且该模式会重复出现任意数量的破折号。次。
抱歉,这可能是一个愚蠢的问题,但是我真的很讨厌正则表达式。
TIA
最佳答案
foundMatch = Regex.IsMatch(subjectString,
@"^ # Start of the string
(?=.*\p{L}) # Assert that there is at least one letter
(?=.*\p{N}) # and at least one digit
(?=.*-) # and at least one dash.
[\p{L}\p{N}-]* # Match a string of letters, digits and dashes
$ # until the end of the string.",
RegexOptions.IgnorePatternWhitespace);
应该做你想做的。如果用字母/数字表示“仅ASCII字母/数字”(而不是国际/ Unicode字母),则使用
foundMatch = Regex.IsMatch(subjectString,
@"^ # Start of the string
(?=.*[A-Z]) # Assert that there is at least one letter
(?=.*[0-9]) # and at least one digit
(?=.*-) # and at least one dash.
[A-Z0-9-]* # Match a string of letters, digits and dashes
$ # until the end of the string.",
RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);