matchRegexp gotcha: Line breaks

Got caught out by this just now – tl;dr if you’re trying to match a regexp at one specific location in the string (not later positions), use findRegexpAt instead of matchRegexp.

(
var str = "0.5 Using
\"regular expressions\" in my parser";

"^\".*\"".matchRegexp(str, 0, 0).debug("string test with limit, I want false");
"^\".*\"".matchRegexp(str).debug("string test without limit, I want false");
"^-?[0-9]".matchRegexp(str, 0, 0).debug("number test with limit, I want true");
"^-?[0-9]".matchRegexp(str).debug("number test without limit, I want true");

string test with limit, I want false: false
string test without limit, I want false: true  // rats... matched the second line
number test with limit, I want true: false  // rats... need to know the length to search
number test without limit, I want true: true
)

(
var str = "0.5 Using
\"regular expressions\" in my parser";

str.findRegexpAt("^\".*\"", 0).notNil.debug("string test with limit, I want false");
str.findRegexpAt("^\".*\"").notNil.debug("string test without limit, I want false");
str.findRegexpAt("^-?[0-9]", 0).notNil.debug("number test with limit, I want true");
str.findRegexpAt("^-?[0-9]").notNil.debug("number test without limit, I want true");
)

string test with limit, I want false: false
string test without limit, I want false: false  // yes
number test with limit, I want true: true  // yes
number test without limit, I want true: true

hjh

1 Like