1

I need to make a regex to match some liquid volumes like:

water in 17oz container
water in container 17oz

How would you make a regex to match these? I could do just /[0-9]{1,}oz/ but that will also match 90ozonelayers, not that it will happen but I want it to be foolproof.

And /[0-9]{1,}oz / will not do the trick to match it if its in the end of the string.

Kristian Rafteseth
  • 2,002
  • 5
  • 27
  • 46

4 Answers4

1

You could use \b to match the word boundary:

/\b[0-9]+oz\b/
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 1
    This is also an incorrect solution, as the word boundary matches any non-word character, ie. `[^a-zA-Z0-9_]`. This means "17oz" from "17ozŵald" would match. – tenub Mar 12 '14 at 13:59
  • Great fine-grained observation, @tenub. Darn Unicode! :} – J0e3gan Mar 19 '14 at 14:25
  • @KristianRafteseth: Consider marking this answer accepted so that others know it was exactly what you were looking for...without having to read the comments. – J0e3gan Mar 19 '14 at 14:26
0

[0-9]{1,}oz(\s|\b)

This matches on your two strings, but doesn't match on something like 12ozsdsds.

EDIT:

Noticing that all solutions are slightly flawed, it seems taking a combination of all things, the best might be something like (stolen bits from tenub):

/(?<=\s|^)[0-9]{1,}oz(?=\s|$)/ (use /g to match all occurrences).

17oz - match

abc 17oz def - match

17ozz - no match

abc17oz - no match

Rhys
  • 1,439
  • 1
  • 11
  • 23
  • This would match "17oz" in "17ozå". – tenub Mar 12 '14 at 13:52
  • That's true, although so would xdazz's, and yours matches `asdasd17oz` (As does mine, so correcting to amalgamate the best of all worlds). – Rhys Mar 12 '14 at 13:59
  • Do note that this would not work for JavaScript due to the lookbehind (although the OP specified PHP so it shouldn't matter). – tenub Mar 12 '14 at 14:15
0

Simple. Just use:

/[0-9]{1,}oz(?= |$)/
tenub
  • 3,386
  • 1
  • 16
  • 25
0

Matches 34oz, 34 oz and 6oz at the end of the string, but not the 56ozone layer.

([0-9]{0,})(\s{0,})(oz{1})(\s{0,}|$)
Andresch Serj
  • 35,217
  • 15
  • 59
  • 101