Сопоставить регулярное выражение со строкой

1

У меня есть текст и хотелось бы получить все вхождения в массив, например:

[
    ['{{ $slot }}'],
    ['{{$example }}'],
    ['{{ $Product2}}'],
    ['{{$category1 }}']
]

Я попробовал следующий пример:

const text = "<h1>Hello world!</h1> <h2>What is {{ $slot }} Ipsum?</h2> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to {{$example }}make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially {{$category1 }} unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more {{ $Product2}} recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <p>&nbsp;</p><p>&nbsp;</p>"

let data = text.match('/{{\s*\$\w+\s*}}')

console.log(data)

Как вы можете видеть, я получаю null как результат.

Любые предложения почему?

Я ценю ваши ответы!

  • 0
    Вы сопоставляете строку, а не регулярное выражение. Кроме того, если бы это было регулярное выражение, оно было бы недействительным. Нужно избежать этих фигурных скобок.
Теги:

4 ответа

2
Лучший ответ

В JavaScript литерал регулярного выражения отличается от строкового литерала, поэтому аргумент match должен быть /{{\s*\$\w+\s*}}/ а не '{{\s*\$\w+\s*}}' или '/{{\s*\$\w+\s*}}'. Обратите внимание, что вокруг него нет кавычек. Так что постарайтесь:

const text = "<h1>Hello world!</h1> <h2>What is {{ $slot }} Ipsum?</h2> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to {{$example }}make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially {{$category1 }} unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more {{ $Product2}} recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <p>&nbsp;</p><p>&nbsp;</p>"
let data = /{{\s*\$\w+\s*}}/g

Который дает:

>>> data
Array(4) [
    "{{ $slot }}",
    "{{ $example }}",
    "{{ $category1 }}",
    "{{ $Product2}}"
]

Обратите внимание, что я добавил флаг g после окончательной косой черты regexp для совпадения, чтобы вернуть все соответствующие строки, а не только первую.

Как заметили другие, также лучше избегать фигурных скобок, иначе у вас возникнут проблемы, когда они будут содержать число, поскольку это имеет особое значение для регулярных выражений.

  • 0
    Исправлено это для вас: D
  • 0
    ой, что глупая ошибка, спасибо ^^
1

попробуйте без первой косой черты

{{\ С *\$\w+\с *}} '

пример regex101

Матч 1:

Полный матч 35-46 {{ $slot }}

Матч 2:

Полный матч 302-315 {{$example }}

Матч 3:

Полный матч 452-467 {{$category1 }}

Матч 4:

Полный матч 589-603 {{ $Product2}}

1

Попробуйте следующее (см. Regex101.com):

const text = "<h1>Hello world!</h1> <h2>What is {{ $slot }} Ipsum?</h2> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to {{$example }}make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially {{$category1 }} unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more {{ $Product2}} recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <p>&nbsp;</p><p>&nbsp;</p>";

let regex = /\{\{\s*(\$[\w_]+)\s*\}\}/g;

let data = text.match(regex);
console.log(data)
1

Просто используйте литерал RegExp и:

  • избегайте $ via \$ чтобы соответствовать буквально символу $ и не утверждать, что конец позиции линии посреди обычного выражения случайно
  • используйте глобальный флаг соответствия g для соответствия каждому вхождению в строку

Подробнее о доступных флажках и символьных классах


Итак, последнее регулярное выражение:

/{{\s*\$\w+\s*}}/g

Рабочий пример:

const text = '<h1>Hello world!</h1> <h2>What is {{ $slot }} Ipsum?</h2> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to {{$example }}make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially {{$category1 }} unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more {{ $Product2}} recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <p>&nbsp;</p><p>&nbsp;</p>'

let data = text.match(/{{\s*\$\w+\s*}}/g)

console.log(data)

ИЛИ ЖЕ

... через конструктор RegExp, просто убедитесь, что вы правильно выбрали классы символов RegExp и уже присутствовали \ символы через ведущий \:

const text = '<h1>Hello world!</h1> <h2>What is {{ $slot }} Ipsum?</h2> <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to {{$example }}make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially {{$category1 }} unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more {{ $Product2}} recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <p>&nbsp;</p><p>&nbsp;</p>'

let data = text.match(new RegExp('{{\\s*\\$\\w+\\s*}}', 'g'))

console.log(data)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню