文字列の途中から特定のテキストと対応するメール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つのキャプチャグループが含まれており、各一致からユーザー名と電子メールを抽出するために使用できます。

電子メールパターン[^,]+は、コンマではない1つ以上の文字と単純に一致します。有効なメールアドレスを保証するものではありません。

これが要件である場合、詳細はここにあります。

実例

Thefourthbird Nov 23 2020 at 10:10

単一のルックビハインドを使用する代わりに、2つのキャプチャグループを使用できます。

\bError importing username: (\d+), primary email: ([^\s@]+@[^\s@,]+)

正規表現のデモ| 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]