정규 표현식 C# - 일치하는 동안 성냥을 추출 할 수 있습니까?
-
20-08-2019 - |
문제
올바른 형식을 확인 해야하는 문자열이 있습니다. 예를 들어 RR1234566-001
(2 글자, 7 자리, 대시, 1 자리 이상). 나는 다음과 같은 것을 사용합니다.
Regex regex = new Regex(patternString);
if (regex.IsMatch(stringToMatch))
{
return true;
}
else
{
return false;
}
이것은 나에게 있는지 말해주기 위해 작동합니다 stringToMatch
정의 된 패턴을 따릅니다 patternString
. 그래도 필요한 것 (그리고 나중에 추출하게됩니다)은 다음과 같습니다.123456
그리고 001
- 즉 stringToMatch
.
이것은 정규 표현을 구성하는 방법에 대한 의문이 아닙니다. 내가 묻는 것은 "나중에 분할 함수를 사용하지 않고 동시에 값을 일치시키고 추출하는 방법이 있습니까?"
해결책
Regex 그룹을 사용하여이를 달성 할 수 있습니다. 예를 들어,이 regex :
(\d\d\d)-(\d\d\d\d\d\d\d)
이 동정인과 함께 전화 번호를 일치 시키자 :
var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
var match = regex.Match("123-4567890");
if (match.Success)
....
일치하면 처음 세 자리를 찾을 수 있습니다.
match.Groups[1].Value
그리고 두 번째 7 자리는 다음과 같습니다.
match.Groups[2].Value
PS C#에서는 @""스타일 문자열을 사용하여 백 슬래시를 피할 수 있습니다. 예를 들어, @" hi "는 " hi "입니다. 정규 표현 및 경로에 유용합니다.
PS2. 첫 번째 그룹은 예상대로 그룹 [0]이 아닌 그룹 [1]에 저장됩니다. 그룹 [0]에 일치하는 전체 문자열이 포함되어 있기 때문입니다.
다른 팁
대신 그룹화 및 성냥을 사용하십시오.
즉:
// NOTE: pseudocode.
Regex re = new Regex("(\\d+)-(\\d+)");
Match m = re.Match(stringToMatch))
if (m.Success) {
String part1 = m.Groups[1].Value;
String part2 = m.Groups[2].Value;
return true;
}
else {
return false;
}
다음과 같이 성냥을 지정할 수도 있습니다.
Regex re = new Regex("(?<Part1>\\d+)-(?<Part2>\\d+)");
그리고 이런 식으로 접근합니다
String part1 = m.Groups["Part1"].Value;
String part2 = m.Groups["Part2"].Value;
괄호를 사용하여 문자 그룹을 캡처 할 수 있습니다.
string test = "RR1234566-001";
// capture 2 letters, then 7 digits, then a hyphen, then 1 or more digits
string rx = @"^([A-Za-z]{2})(\d{7})(\-)(\d+)$";
Match m = Regex.Match(test, rx, RegexOptions.IgnoreCase);
if (m.Success)
{
Console.WriteLine(m.Groups[1].Value); // RR
Console.WriteLine(m.Groups[2].Value); // 1234566
Console.WriteLine(m.Groups[3].Value); // -
Console.WriteLine(m.Groups[4].Value); // 001
return true;
}
else
{
return false;
}
string text = "RR1234566-001";
string regex = @"^([A-Z a-z]{2})(\d{7})(\-)(\d+)";
Match mtch = Regex.Matches(text,regex);
if (mtch.Success)
{
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
Console.WriteLine(m.Groups[3].Value);
Console.WriteLine(m.Groups[4].Value);
return true;
}
else
{
return false;
}
제휴하지 않습니다 StackOverflow