Brandon Wilson
Brandon Wilson

Reputation: 4600

Regex Group Multiple Lines

I am trying to extract DB_NAME, DB_USER, DB_HOST, DB_PASSWORD from a WordPress file using regex. Is there a way to group each variable into its own group?

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'stack');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

Result should be grouped like this: wordpress, root, stack, localhost There should be 4 matches.

Upvotes: 0

Views: 636

Answers (1)

user8397947
user8397947

Reputation: 1544

The below regex is what you're looking for.

define\('DB_(?:NAME|USER|PASSWORD|HOST)', ?'(.*)'\);

It matches entire statements (because JavaScript doesn't support lookbehinds) this way:

  • define\( is the beginning (note the backslash before the parenthesis)
  • 'DB_(?:NAME|USER|PASSWORD|HOST)' is the variable name
  • , ? is the delimiter between the variable name and the actual value
  • '(.*)' is the actual value (use '(.+)' if the values aren't allowed to be empty)
  • \); is the end (again, note the backslash before the parenthesis)

Note that the actual value is in a capture group (kudos to Casimir et Hippolyte for suggesting this). Not only this is easier to set up than lookarounds, but it works on JS unlike what I came up previously.

Upvotes: 2

Related Questions