我需要匹配这个字符串 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);
关于c# - 使用正则表达式匹配包含数字字母和破折号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5191754/