문자열 중간에서 특정 텍스트 및 해당 이메일 ID를 찾아 데이터 테이블 또는 C #의 목록에 저장
Nov 23 2020
다음과 같은 문자열이 있습니다.
string error_message= "{\"2705\":\"Error importing username: 3167763, primary email: [email protected], error: User already exists but Email does not match: [email protected] vs [email protected]\",\"10001\":\"Error importing username: 3195330, primary email: [email protected], error: User already exists but Email does not match: [email protected] vs [email protected]\"}";
위의 문자열에서 "Error importing username :"이라는 반복 텍스트를 찾아서 "primary email :"텍스트 뒤에 해당 이메일 ID와 함께 그 옆에있는 사용자 이름 값을 가져 와서 아래와 같이 예상 출력과 함께 데이터 테이블에 저장해야합니다.
Datatable의 예상 결과는 아래와 같습니다.
username primary email
3167763 [email protected]
3195330 [email protected]
아래는 목록의 모든 사용자 이름을 가져올 수있는 코드 샘플입니다. 사용자 이름과 해당 기본 이메일 ID를 모두 가져 오기 위해 아래 코드를 수정해야합니다. 컬렉션에서 도움이 매우 유용 할 것입니다.
List<int> list = Regex.Matches(error_message, @"(?<=Error importing username: )\d+")
.Cast<Match>()
.Select(match => int.Parse(match.Value))
.ToList();
답변
JohnathanBarclay Nov 23 2020 at 10:06
사용자 이름을 키로, 이메일을 값으로 사용하여 사전을 만들 수 있습니다.
string pattern = @"Error importing username: (\d+), primary email: ([^,]+)";
var dict = Regex.Matches(error_message, pattern)
.Cast<Match>()
.ToDictionary(match => match.Groups[1], match => match.Groups[2]);
패턴에는 괄호로 표시된 2 개의 캡처 그룹이 포함되어 있으며 각 일치 항목에서 사용자 이름과 이메일을 추출하는 데 사용할 수 있습니다.
이메일 패턴은 [^,]+
단순히 쉼표가 아닌 하나 이상의 문자와 일치합니다. 유효한 이메일 주소를 보장하지 않습니다.
이것이 요구 사항 인 경우 여기 에서 자세한 내용을 확인할 수 있습니다 .
작업 예
Thefourthbird Nov 23 2020 at 10:10
단일 lookbehind를 사용하는 대신 2 개의 캡처 그룹을 사용할 수 있습니다.
\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)
Regex 데모 | C # 데모
예를 들면
string pattern = @"\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)";
string input = @"string error_message= ""{\""2705\"":\""Error importing username: 3167763, primary email: [email protected], error: User already exists but Email does not match: [email protected] vs [email protected]\"",\""10001\"":\""Error importing username: 3195330, primary email: [email protected], error: User already exists but Email does not match: [email protected] vs [email protected]\""}"";";
var collection = Regex.Matches(input, pattern)
.Cast<Match>()
.Select(match =>
new {username = int.Parse(match.Groups[1].Value), primary_email = match.Groups[2].Value}
);
foreach (var item in collection) {
Console.WriteLine("username: {0}, primary email: {1}",
item.username,
item.primary_email
);
}
산출
username: 3167763, primary email: [email protected]
username: 3195330, primary email: [email protected]