eternalthinker
eternalthinker

Reputation: 532

Regex not parsing consecutive occurrences of pattern

I am trying to write a regex in JavaScript to parse occurrences of patterns like \123 into corresponding ASCII value of the number. 65 is replaced by A and so on.

\ itself can be escaped as \\, so that \\65 becomes \65.

The issue I am facing is, consecutive occurrences of the main pattern isn't parsed correctly.
\65#\97 becomes A#a. But \65\97 only becomes A\97.

Core part of the code is given below:

// Parse \65 but not \\65
input = input.replace(/(^|[^\\]{1})\\(\d{1,3})/g, function (m0, m1, m2) {
    var n = parseInt(m2);
    if (n < 256) {
        return m1 + String.fromCharCode(n);
    } else {
        return m0;
    }
});  

A fiddle illustrating the same is available here

I'd guess the error has to do with the regex, but none I can figure out as of yet.
Awaiting any insights on the same :]

Upvotes: 0

Views: 66

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

I think the simple answer is to match a backslash followed by either a backslash or a digit sequence. If it's followed by a digit sequence, check the value and do your substitution:

var input = "Do these: \\65\\97 \\66#\\97 But not: \\\\65\\\\97 Do this: \\\\\\65";
snippet.log("Before: " + input);
input = input.replace(/\\(\\|\d+)/g, function(m, c) {
  var val;
  if (c !== "\\") {
    val = +c;
    if (val >= 0 && val <= 255) {
      return String.fromCharCode(val);
    }
  }
  return m;
});
snippet.log("After: " + input);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

Guffa
Guffa

Reputation: 700262

You can catch both \\ and codes like \97 in the regular expression, and leave \\ and codes above 255 unchanged:

var input = "\\\\42This is \\97 \\116\\101st.\\\\256";

input = input.replace(/(\\\\|\\\d{1,3})/g, function (m) {
  if (m != '\\\\') {  
    var n = parseInt(m.substr(1), 10);
    if (n < 256) {
       m = String.fromCharCode(n);
    }
  }
  return m;
});

document.write(input);

Upvotes: 1

Related Questions