Как извлечь разделенные запятыми подстроки из строки? - PullRequest
2 голосов
/ 25 мая 2019

Необходимо проанализировать алгоритмы, разделенные запятой, в группе.

SSH Enabled - version 2.0
Authentication methods:publickey,keyboard-interactive,password
Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
MAC Algorithms:hmac-sha1,hmac-sha1-96
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):

Я пытался разделить их запятой, но не получил ожидаемых результатов:

^Encryption Algorithms:(.*?)(?:,|$)

Ожидаемые результатыиметь каждый алгоритм в группе 1 без пустой группы

aes128-ctr
aes192-ctr
aes256-ctr
aes128-cbc
3des-cbc
aes192-cbc
aes256-cbc

Ответы [ 2 ]

1 голос
/ 26 мая 2019

Другим способом может быть сопоставление строки, начинающейся с Encryption Algorithms:, а затем захватывание в группе повторяющегося шаблона, который сопоставляет деталь с дефисом и повторяет ее с добавлением запятой.

Если естьсовпадение, вы можете разделить первую группу захвата на запятую.

^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)

Пояснение

  • ^
  • Encryption Algorithms:
  • ( Начало группы захвата
    • \w+-\w+ Совпадение с 1+ символами слов, - и 1+ словами символов
    • (?:,\w+-\w+)* 0+ раз повторить aзапятая, за которой следуют 1+ слов, - и 1+ слов
  • ) Закрыть группу захвата

Regex demo | Python demo

import re
regex = r"^Encryption Algorithms:(\w+-\w+(?:,\w+-\w+)*)"
test_str = ("SSH Enabled - version 2.0\n"
            "Authentication methods:publickey,keyboard-interactive,password\n"
            "Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc\n"
            "MAC Algorithms:hmac-sha1,hmac-sha1-96\n"
            "Authentication timeout: 120 secs; Authentication retries: 3\n"
            "Minimum expected Diffie Hellman key size : 1024 bits\n"
            "IOS Keys in SECSH format(ssh-rsa, base64 encoded):")

matches = re.search(regex, test_str, re.MULTILINE)
if matches:
    print(matches.group(1).split(","))

Результат:

['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', '3des-cbc', 'aes192-cbc', 'aes256-cbc']
1 голос
/ 25 мая 2019

Это может быть не самый лучший способ, однако это может быть один из способов разделить нашу строку на три части, возможно, даже прежде, чем запустить ее через движок RegEx.Если это не так, и мы хотим иметь выражение, это может быть близко:

(.+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC.+)

enter image description here


Если вы такжеесть новые строки, которые вы можете захотеть проверить с другими выражениями, например:

([\s\S]+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC[\s\S]+)

([\w\W]+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC[\w\W]+)

([\d\D]+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC[\d\D]+)

Демо 1

Демонстрация 2

RegEx

Если это выражение нежелательно, его можно изменить или изменить в regex101.com .

RegEx Circuit

jex.im визуализирует регулярные выражения:

enter image description here

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([\w\W]+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC[[\w\W]+)"

test_str = ("SSH Enabled - version 2.0\n"
    "Authentication methods:publickey,keyboard-interactive,password\n"
    "Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc\n"
    "MAC Algorithms:hmac-sha1,hmac-sha1-96\n"
    "Authentication timeout: 120 secs; Authentication retries: 3\n"
    "Minimum expected Diffie Hellman key size : 1024 bits\n"
    "IOS Keys in SECSH format(ssh-rsa, base64 encoded):\n")

subst = "\\2 "

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Демо

const regex = /(.+Encryption Algorithms:)|([a-z0-9-]+)(?:,|\s)|(MAC.+)/gm;
const str = `SSH Enabled - version 2.0 Authentication methods:publickey,keyboard-interactive,password Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc MAC Algorithms:hmac-sha1,hmac-sha1-96 Authentication timeout: 120 secs; Authentication retries: 3 Minimum expected Diffie Hellman key size : 1024 bits IOS Keys in SECSH format(ssh-rsa, base64 encoded):`;
const subst = `$2 `;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);
...