Javascript preg match all

preg_match_all JS equivalent?

Is there an equivalent of PHP’s preg_match_all in Javascript? If not, what would be the best way to get all matches of a regular expression into an array? I’m willing to use any JS library to make it easier.

Answers

You can use match with the global modifier:

1) /^[d]+$/ 2) /^([u0600-u06FF]+s)*[u0600-u06FF]+$/ 3) /^([u0600-u06FF]+d*s)*[u0600-u06FF]+d*$/ 

/u is not supported, since Javascript regexes only supports unicode in terms of codepoints. x <. >(unicode codepoints) should be written u. in Javascript regex (always 4 digits 0 padded)

In these cases, the following applies to the rest of the regex:

  • s in Javascript is treated as unicode
  • d isn’t, which means only ASCII digits (0-9) are accepted.

This means we specifically have to allow «foreign» numerals, e.g. Persian (codepoints 06F0-06F9):

1) /^[du06F0-u06F9]+$/ 2) /^([u0600-u06FF]+s)*[u0600-u06FF]+$/ 3) /^([u0600-u06FF]+[du06F0-u06F9]*s)*[u0600-u06FF]+[du06F0-u06F9]*$/ 

(Remove d if ASCII digits shouldn’t be accepted)

Not sure what the brackets are supposed to be doing in example 1, originally they could be written:

But to add the Persian numerals, we need them, see above.

Spry character masking, however, only wants a regex to be applied on each entered character — i.e., we can’t actually do pattern matching, it’s just a «list» of accepted characters in all places, in which case:

1 ) /[u06F0-u06F9d]/ // match 0-9 and Persian numerals 2 and 3) /[u0600-u06FFds]/ // match all Persian characters (includes numerals), 0-9 and space 

Once again, remove d if you don’t want to accept 0-9.

Now. using regex for validation with Spry:

var checkFullName = function(value, options) < // Match with the by now well-known regex: if (value.match(/^([u0600-u06FF]+s)*[u0600-u06FF]+$/)) < return true; >return false; > var sprytextfield = new Spry.Widget.ValidationTextField( "sprytextfield", "custom", < validation: checkFullName, validateOn: ["blur", "change"] >); 

A similar custom function can be made for case 3.

Читайте также:  Html editor asp net

See examples from Adobe labs

Источник

preg_match_all JS equivalent?

Is there an equivalent of PHP’s preg_match_all in Javascript? If not, what would be the best way to get all matches of a regular expression into an array? I’m willing to use any JS library to make it easier.

Answers

You can use match with the global modifier:

1) /^[d]+$/ 2) /^([u0600-u06FF]+s)*[u0600-u06FF]+$/ 3) /^([u0600-u06FF]+d*s)*[u0600-u06FF]+d*$/ 

/u is not supported, since Javascript regexes only supports unicode in terms of codepoints. x <. >(unicode codepoints) should be written u. in Javascript regex (always 4 digits 0 padded)

In these cases, the following applies to the rest of the regex:

  • s in Javascript is treated as unicode
  • d isn’t, which means only ASCII digits (0-9) are accepted.

This means we specifically have to allow «foreign» numerals, e.g. Persian (codepoints 06F0-06F9):

1) /^[du06F0-u06F9]+$/ 2) /^([u0600-u06FF]+s)*[u0600-u06FF]+$/ 3) /^([u0600-u06FF]+[du06F0-u06F9]*s)*[u0600-u06FF]+[du06F0-u06F9]*$/ 

(Remove d if ASCII digits shouldn’t be accepted)

Not sure what the brackets are supposed to be doing in example 1, originally they could be written:

But to add the Persian numerals, we need them, see above.

Spry character masking, however, only wants a regex to be applied on each entered character — i.e., we can’t actually do pattern matching, it’s just a «list» of accepted characters in all places, in which case:

1 ) /[u06F0-u06F9d]/ // match 0-9 and Persian numerals 2 and 3) /[u0600-u06FFds]/ // match all Persian characters (includes numerals), 0-9 and space 

Once again, remove d if you don’t want to accept 0-9.

Now. using regex for validation with Spry:

var checkFullName = function(value, options) < // Match with the by now well-known regex: if (value.match(/^([u0600-u06FF]+s)*[u0600-u06FF]+$/)) < return true; >return false; > var sprytextfield = new Spry.Widget.ValidationTextField( "sprytextfield", "custom", < validation: checkFullName, validateOn: ["blur", "change"] >); 

A similar custom function can be made for case 3.

Читайте также:  Input type search php

See examples from Adobe labs

Источник

preg_match_all эквивалент JS?

Есть ли в Javascript эквивалент PHP preg_match_all? Если нет, то как лучше всего записать все совпадения регулярного выражения в массив? Я готов использовать любую библиотеку JS, чтобы упростить задачу.

4 ответы

Вы можете использовать match с глобальным модификатором:

Я не понял этого синтаксиса. — м3нда

Обратите внимание, что этот подход игнорирует захваты. ‘1a 2b 3c 4d’.match(/(\d)([a-z])/g) выводит только [«1a», «2b», «3c», «4d»] . Если вам нужны снимки, см. этот ответ — Клесун

Джон Ресиг написал об отличной технике в своем блоге под названием ‘Искать и не заменять’

Он работает с использованием функции замены javascript, которая принимает функцию обратного вызова и ничего не возвращает, чтобы исходное содержимое оставалось неизменным.

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

Лучшим эквивалентом preg_match_all из PHP в JS было бы использование функции exec (). Это также позволит вам захватывать группы, с match () вы не можете этого сделать.

Например, вы хотите записать все времена и число в скобках из переменной myString:

var myString = "10:30 am (15 left)11:00 am (15 left)11:30 am"; var pattern = /(\d:\d\s?[ap]m)\s\((\d+)/gi; var match; while (match = pattern.exec(myString)) < console.log('Match: "' + match[0] + '" first group: ->"' + match[1] + '" second group -> ' + match[2]); > 
Match: "10:30 am (15" first group: -> "10:30 am" second group -> 15 Match: "11:00 am (15" first group: -> "11:00 am" second group -> 15 

Источник

Оцените статью