Home > Net >  Need to find First Word Using Regular Expression
Need to find First Word Using Regular Expression

Time:09-30

HI I have string like var Sql=" INSERT INTO DB.SCHEMA.TABLE VALUES(?,?,?)" Regex pattern i am using (?<=INSERT INTO\b).*; which is producing the result as DB.SCHEMA.TABLE VALUES(?,?,?).

But i need first word immediately after INSERT INTO , which is in this case DB.SCHEMA.TABLE.

What additional expression i should add to Regex pattern to get only first word after Insert Into

CodePudding user response:

You can use

const text = `var Sql=" INSERT INTO DB.SCHEMA.TABLE VALUES(?,?,?)"`;
const regex = /\bINSERT\s INTO\s (\w (?:\.\w )*|`[^`]*`)/g;
const results = Array.from(text.matchAll(regex), (x) => x[1]);
console.log(results);

See the regex demo. Details:

  • \bINSERT - whole word INSERT
  • \s - one or more whitespaces
  • INTO - an INTO word
  • \s - one or more whitespaces
  • (\w (?:.\w )*|`[^`]*`) - Group 1: one or more word chars and then zero or more occurrences of . and one or more word chars, or a backtick, zero or more chars other than backtick and then a backtick char.
  • Related