Home > Software design >  regex matches in php, but not in javascript
regex matches in php, but not in javascript

Time:10-08

I have the folowing text

00:00:01.000 --> 00:00:02.000
ALFRED, NOČNI ČUVAJ

and with this regex:

/(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{3})/

and a bit of code:

<?php

$line = "00:00:01.000 --> 00:00:02.000\r\nALFRED, NOČNI ČUVAJ";
$pattern1 = '(\d{2}):(\d{2}):(\d{2})\.(\d{3})';

$m1 = preg_match("/^$pattern1/", $line);
if (is_numeric($m1) && $m1 > 0)
{
    echo preg_replace("/$pattern1/", '$1:$2:$3,$4', $line);
}

I am matching: 00:00:01.000 --> 00:00:02.000 and replacing it with 00:00:01,000 --> 00:00:02,000

so at the end I get this out

00:00:01,000 --> 00:00:02,000
ALFRED, NOČNI ČUVAJ

it all works fine in php, example: https://www.tehplayground.com/nZkox8mkNVaC3hW6

the problem is when I got to javascript and want to do the same thing (same regex patern (even https://regexr.com/ confirned that the patern does match 00:00:01.000 --> 00:00:02.000)

function preg_match(pattern, str) {
  var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])   1),
    _pattern = pattern.substr(1, pattern.lastIndexOf(pattern[0]) - 1);
  return (new RegExp(_pattern, _flag)).test(str);
}
/**
 * preg_replace (from PHP) in JavaScript!
 *
 * This is basically a pattern replace. You can use a regex pattern to search and 
 * another for the replace. For more information see the PHP docs on the original 
 * function (http://php.net/manual/en/function.preg-replace.php), and for more on 
 * JavaScript flavour regex visit http://www.regular-expressions.info/javascript.html
 *
 * NOTE: Unlike the PHP version, this function only deals with string inputs. No arrays.
 *
 * @author  William Duyck <[email protected]>
 * @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 * 
 * @param   {String}    pattern The pattern to search for.
 * @param   {String}    replace The string to replace.
 * @param   {String}    subject The string to search and replace.
 * @param   {Integer}   limit   The maximum possible replacements.
 * @return  {String}    If matches are found, the new subject will be returned.
 */
var preg_replace = function(pattern, replace, subject, limit) {
  if (limit === undefined) {
    limit = -1;
  }

  var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])   1),
    _pattern = pattern.substr(1, pattern.lastIndexOf(pattern[0]) - 1),
    reg = new RegExp(_pattern, _flag),
    rs = null,
    res = [],
    x = 0,
    y = 0,
    rtn = subject;

  var tmp = [];
  if (limit === -1) {
    do {
      tmp = reg.exec(subject);
      if (tmp !== null) {
        res.push(tmp);
      }
    } while (tmp !== null && _flag.indexOf('g') !== -1);
  } else {
    res.push(reg.exec(subject));
  }
  for (x = res.length - 1; x > -1; x--) {
    tmp = replace;

    for (y = res[x].length; y > -1; y--) {
      tmp = tmp.replace('${'   y   '}', res[x][y])
        .replace('$'   y, res[x][y])
        .replace('\\'   y, res[x][y]);
    }
    rtn = rtn.replace(res[x][0], tmp);
  }
  return rtn;
};

line = "00:00:01.000 --> 00:00:02.000\r\nALFRED, NOČNI ČUVAJ";
pattern1 = '(\\d{2}):(\\d{2}):(\\d{2})\.(\\d{3})';

m1 = preg_match("/^"   pattern1   "/", line);
if (m1) {
  console.log(preg_replace("/"   pattern1   "/", '$1:$2:$3,$4', line));
}

Example: https://jsfiddle.net/a2mzkhew/

as you can see I get this out

00:00:01,000 --> 00:00:02.000
ALFRED, NOČNI ČUVAJ

as you can see only first word (00:00:01,000) til --> is matched, the other one (00:00:02.000) is not

What am I doing wrong that I have so diferent results if I swich languages (I tried to make things as similar as possible (even replicating regex_match and regex_replace in javascript) so this will not happen

Thanks for Anwsering

CodePudding user response:

You are not searching for more than one match. Adding g to your regular expression will make it do both replacements

function preg_match(pattern, str) {
  var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])   1),
    _pattern = pattern.substr(1, pattern.lastIndexOf(pattern[0]) - 1);
  return (new RegExp(_pattern, _flag)).test(str);
}
var preg_replace = function(pattern, replace, subject, limit) {
  if (limit === undefined) {
    limit = -1;
  }

  var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])   1),
    _pattern = pattern.substr(1, pattern.lastIndexOf(pattern[0]) - 1),
    reg = new RegExp(_pattern, _flag),
    rs = null,
    res = [],
    x = 0,
    y = 0,
    rtn = subject;

  var tmp = [];
  if (limit === -1) {
    do {
      tmp = reg.exec(subject);
      if (tmp !== null) {
        res.push(tmp);
      }
    } while (tmp !== null && _flag.indexOf('g') !== -1);
  } else {
    res.push(reg.exec(subject));
  }
  for (x = res.length - 1; x > -1; x--) {
    tmp = replace;

    for (y = res[x].length; y > -1; y--) {
      tmp = tmp.replace('${'   y   '}', res[x][y])
        .replace('$'   y, res[x][y])
        .replace('\\'   y, res[x][y]);
    }
    rtn = rtn.replace(res[x][0], tmp);
  }
  return rtn;
};

line = "00:00:01.000 --> 00:00:02.000\r\nALFRED, NOČNI ČUVAJ";
pattern1 = '(\\d{2}):(\\d{2}):(\\d{2})\.(\\d{3})';

m1 = preg_match("/^"   pattern1   "/g", line);
if (m1) {
  console.log(preg_replace("/"   pattern1   "/g", '$1:$2:$3,$4', line));
}

CodePudding user response:

So, your question was: "how to convert 00:00:01.000 --> 00:00:02.000 to 00:00:01,000 --> 00:00:02,000 in JavaScript"?

const line = "00:00:01.000 --> 00:00:02.000\r\nALFRED, NOČNI ČUVAJ";
const result = line.replace(/\b(?<=\d{2}:\d{2}:\d{2}).(?=\d{3})\b/g, ",");

console.log(result);

which basically replaces the "." with "," given a positive lookbehind (?<=) pattern and a positive lookahead (?=) pattern, where \b stands for Word Boundary.

  • Related