#regex #sorting
#регулярное выражение #сортировка
Вопрос:
Я хочу отсортировать электронное письмо: пароль по первому вхождению каждого электронного письма.
Пример списка:
email@example.com:passsword1
email@example.com:passsword2
email@example.com:passsword3
email1@example.com:passsword1
email1@example.com:passsword2
email1@example.com:passsword2
Так что только
email@example.com:passsword1
email1@example.com:passsword1
должно быть сохранено как результат.
С моими ограниченными навыками регулярных выражений я разобрался с этим, но, думаю, я что-то неправильно понимаю:
^(.*)(r?n1) (?=:)
Комментарии:
1. Использование регулярных выражений для этого — безумие.
Ответ №1:
Используйте
^((.*:).*)(?:r?n2.*)
См. Доказательство, использование g
и m
флаги.
Объяснение
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
( group and capture to 2:
--------------------------------------------------------------------------------
.* any character except n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
) end of 2
--------------------------------------------------------------------------------
.* any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
(?: group, but do not capture (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
r? 'r' (carriage return) (optional
(matching the most amount possible))
--------------------------------------------------------------------------------
n 'n' (newline)
--------------------------------------------------------------------------------
2 what was matched by capture 2
--------------------------------------------------------------------------------
.* any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of grouping