Collapsible units with javascript regex

Let's say I have a string that contains some units (which may or may not have prefixes) that I want to split into separate units. For example, a string may contain “Btu (th)” or “Btu (th) .ft” or even “mBtu (th) .ft”, where mBtu (th) is the milli thermochemical BTU bastard unit (this is just an example),

I currently have the following (simplified) regular expression, but it is not suitable for the case of "mBtu (th) .ft":

/(m|k)??(Btu\(th\)|ft|m)(?:\b|\s|$)/g

Currently, this incorrectly defines the boundary between the end of "Btu (th)" and the beginning of "ft". I understand that javascript regex does not support appearance, so how do I parse the string exactly?

Additional notes

  • The regex presented above is greatly simplified around groups of prefixes and units. Prefixes can span multiple characters, such as "Ki", ​​and therefore character sets are not suitable.
  • It is desirable that each group catch the prefix match as group 1, and the unit matches two, i.e. for "mBtu (th) .ft" a match would be ['m', 'Btu (th)'] and a match of two would be ['', 'ft'].
  • Matching the prefix should be lazy, so the string 'm' will be matched as units, not prefix milli. Similarly, for "mm" there must be a prefix of milli and units.
+4
source share
3 answers

I would try:

/((m)|(k)|(Btu(\(th\))?)|(ft)|(m)|(?:\.))+/g

, , . DEMO

(DEMO):

/(?:(m)|(k)|(Btu)|(th)|(ft)|[\.\(\)])/g

, $1, $2, $3, $4 .. (DEMO), . ., (, ). , , .

, , , :

/(m|k|Btu|th|ft)/g 
+2

. , , . , , :

[mk]??(Btu\(th\)|ft|m)(?!\w)

0

I believe that you are behind something like this. If I understand correctly that I want to match an element, perhaps the previous character mor kand separated by brackets or dots.

/[\s\.\(]*(m|k?)(\w+)[\s\.\)]*/g

https://regex101.com/r/eQ5nR4/2

If you don't need to match parentheses, but just return items you can just do

/(m|k?)(\w+)/g

https://regex101.com/r/oC1eP5/1

0
source

All Articles