전화 번호로 10 자리 휴대폰 번호 를 정규식으로 만들고 싶습니다 . 예는
9088534816
+91 33 40653155
033-2647-0969
다음 과 같은 세 가지 형식을 모두 일치시킬 수 있는 정규식을 만들고 싶습니다.
xxxxxxxxxx
+xx xx xxxxxxxx
xxx-xxxx-xxxx
형식. 누구든지 나를 도울 수 있습니까? 나는 이것을 시도했다
\+?\d[\d -]{8,12}\d
하지만이 숫자도 12115351689385를 사용하고 있습니다. 그게 제 문제입니다.
각 패턴을 별도로 설계하고 테스트합니다 .
Format Pattern
-------------------------------------------------
xxxxxxxxxx ^[0-9]{10}$
+xx xx xxxxxxxx ^\+[0-9]{2}\s+[0-9]{2}\s+[0-9]{8}$
xxx-xxxx-xxxx ^[0-9]{3}-[0-9]{4}-[0-9]{4}$
....
그런 다음 마지막으로 결합 하십시오.
(pattern1)|(pattern2)|...|(patternN)
위의 세 패턴에 대해 결합 된 패턴은
(^[0-9]{10}$)|(^\+[0-9]{2}\s+[0-9]{2}[0-9]{8}$)|(^[0-9]{3}-[0-9]{4}-[0-9]{4}$)
다음과 같이 구현할 수 있습니다.
//TODO: you may want to load the patterns supported from resource, file, settings etc.
private static string[] m_Patterns = new string[] {
@"^[0-9]{10}$",
@"^\+[0-9]{2}\s+[0-9]{2}[0-9]{8}$",
@"^[0-9]{3}-[0-9]{4}-[0-9]{4}$",
};
private static string MakeCombinedPattern() {
return string.Join("|", m_Patterns
.Select(item => "(" + item + ")"));
}
테스트 :
string[] tests = new string[] {
"9088534816",
"+91 33 40653155",
"033-2647-0969",
"123",
"12115351689385",
};
var result = string
.Join(Environment.NewLine, tests
.Select(test =>
$"{test,18} {(Regex.IsMatch(test, MakeCombinedPattern()) ? "yes" : "no"),3}"));
Console.Write(result);
결과:
9088534816 yes
+91 33 40653155 yes
033-2647-0969 yes
123 no
12115351689385 no
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다