JZ.
JZ.

Reputation: 21877

regex to match partial strings and fragments of sentences

Suppose I wish to match the following with a regular expression:

Convert 2g of NaOH into moles.
Convert 3.2 grams of Chlorine into mol.
How many moles are in 67 g of Sodium Chloride?
434 mol of Sodium to Grams. 

The requirements are:

How could I use a single regex to match all 4 cases?

So far I have tried this:

~'mol|g|Grams/g

but it also matches terms such as:

32 mol
gravity of molecule 

Upvotes: 0

Views: 1836

Answers (1)

Bohemian
Bohemian

Reputation: 425043

This regex requires both "mol"/"moles" and "g"/"grams" (allowing the "g" to immediately follow a digit):

/^(?=.*\bmol(es)?\b)(?=.*[^a-z](g|grams?)\b).*/i

The use of \b - word boundary - ensures "molecule" and "good" don't count as matches etc.

The "i" flag makes it case insensitive.

See demo

Upvotes: 2

Related Questions