Home > Back-end >  Regex not working when using [.] instead of .
Regex not working when using [.] instead of .

Time:10-08

I want to parse a SQL select intruction. E.g. in JavaScript:

a = 'select a, b from c, d where e'

/((select[\s]*(. ))(from(. ))(where(. )))/.exec(a)

This captures 'a, b' in group 3.

However, if there is a newline between 'a,' and 'b', the regex breaks because '.' does not capture newlines. Therefore, I tried switching the first (. ) for ([.\n\r] ) but it does not work. Even if there is no newline, ([.] ) cannot replace (. ):

((select[\s]*([.] ))(from(. ))(where(. )))

Why not if [abc] means 'any of a, b or c'?

CodePudding user response:

Because [.] matches a literal .; using a character class is one way to change . from meaning "any character" to just matching itself (the other of course being a backslash).

If you want the set of characters matched by . to include newlines, you have to set "single-line" mode by adding the /s flag to the regex:

> "foo\nbar".match(/foo.bar/)
null
> "foo\nbar".match(/foo.bar/s)
[ 'foo\nbar', index: 0, input: 'foo\nbar', groups: undefined ]
  • Related