0

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:

  • Both the terms g/grams and mol/moles need to appear in the string
  • These terms must be on their own, i.e. not as parts of longer words like molecules.

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 
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
JZ.
  • 21,147
  • 32
  • 115
  • 192

1 Answers1

2

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

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Bohemian
  • 412,405
  • 93
  • 575
  • 722