У меня есть текст и хотелось бы получить все вхождения в массив, например:
[
['{{ $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'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> </p><p> </p>"
let data = text.match('/{{\s*\$\w+\s*}}')
console.log(data)
Как вы можете видеть, я получаю null
как результат.
Любые предложения почему?
Я ценю ваши ответы!
В 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'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> </p><p> </p>"
let data = /{{\s*\$\w+\s*}}/g
Который дает:
>>> data
Array(4) [
"{{ $slot }}",
"{{ $example }}",
"{{ $category1 }}",
"{{ $Product2}}"
]
Обратите внимание, что я добавил флаг g
после окончательной косой черты regexp для совпадения, чтобы вернуть все соответствующие строки, а не только первую.
Как заметили другие, также лучше избегать фигурных скобок, иначе у вас возникнут проблемы, когда они будут содержать число, поскольку это имеет особое значение для регулярных выражений.
попробуйте без первой косой черты
{{\ С *\$\w+\с *}} '
Матч 1:
Полный матч 35-46
{{ $slot }}
Матч 2:
Полный матч 302-315
{{$example }}
Матч 3:
Полный матч 452-467
{{$category1 }}
Матч 4:
Полный матч 589-603
{{ $Product2}}
Попробуйте следующее (см. 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'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> </p><p> </p>";
let regex = /\{\{\s*(\$[\w_]+)\s*\}\}/g;
let data = text.match(regex);
console.log(data)
Просто используйте литерал 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'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> </p><p> </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'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> </p><p> </p>'
let data = text.match(new RegExp('{{\\s*\\$\\w+\\s*}}', 'g'))
console.log(data)