Как вы понимаете регулярные выражения, которые написаны в одной строке?

StackOverflow https://stackoverflow.com/questions/3596441

  •  02-10-2019
  •  | 
  •  

Вопрос

Это аккуратно хорошо документированное регулярное выражение, легко понять, поддерживать и модифицировать.

    text = text.replace(/
    (                               // Wrap whole match in $1
        (
            ^[ \t]*>[ \t]?          // '>' at the start of a line
            .+\n                    // rest of the first line
            (.+\n)*                 // subsequent consecutive lines
            \n*                     // blanks
        )+
    )
    /gm,

Но как вы ходите по работе с ними?

text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm,

Есть ли красивый какого-то вида, которое имеет смысл и описывает его функциональность?

Это было полезно?

Решение

Regexbuddy. будет «перевести» любое регулярное выражение для вас. При подаче заявки Regex он выводит:

((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)

Options: ^ and $ match at line breaks

Match the regular expression below and capture its match into backreference number 1 «((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)»
   Match the regular expression below and capture its match into backreference number 2 «(^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Note: You repeated the capturing group itself.  The group will capture only the last iteration.  
          Put a capturing group around the repeated group to capture all iterations. «+»
      Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
      Match a single character present in the list below «[ \t]*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
         The character “ ” « »
         A tab character «\t»
      Match the character “>” literally «>»
      Match a single character present in the list below «[ \t]?»
         Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
         The character “ ” « »
         A tab character «\t»
      Match any single character that is not a line break character «.+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Match a line feed character «\n»
      Match the regular expression below and capture its match into backreference number 3 «(.+\n)*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
         Note: You repeated the capturing group itself.  The group will capture only the last iteration.  
             Put a capturing group around the repeated group to capture all iterations. «*»
         Match any single character that is not a line break character «.+»
            Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
         Match a line feed character «\n»
      Match a line feed character «\n*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»

Это выглядит довольно пугающим в текстовой форме, но гораздо более читаемо в формате HTML (которая не может быть воспроизведена здесь) или в самом RegexBuddy. Он также указывает на обычные Gotchas (например, повторяющиеся захватывающие группы, которые, вероятно, не хотели здесь).

Другие советы

Стоит усилия, чтобы стать искусным на чтении Regexs в одной линии. Большую часть времени там написано таким образом

мне нравиться экспресс

Через некоторое время я получил, чтобы читать вещи. Большое для большинства Regexes нет, и я рекомендую сайт http://www.regular-expressions.info/ Если вы хотите использовать их чаще.

Регулярные выражения - это просто способ выражения масок и т. Д. В конце это просто «язык» со своим собственным синтаксисом.
Комментарий Каждый бит вашего регулярного выражения будет то же самое, что комментирует каждую строку вашего проекта.
Конечно, это поможет людям, которые не понимают ваш код, но это просто бесполезно, если вы (разработчик) понимаете значение Regex.

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top