Javascript regular expression: match anything up until something (if there it exists)

undefinederror picture undefinederror · Dec 21, 2011 · Viewed 38.4k times · Source

Hi I am new to regular expression and this may be a very easy question (hopefully).

I am trying to use one solution for 3 kind of string

  • "45%", expected result: "45"
  • "45", expected result: "45"
  • "", expected result: ""

What I am trying (let the string be str):

str.match(/(.*)(?!%*)/i)[1]

This in my head would sound like "match any instance of anything up until '%' if it is found, or else just match anything"

In firebug's head it seems to sound more like "just match anything and completely disregard the negative lookahead". Also to make it lazy - (.*)? - doesn't seem to help.

Let's forget for a second that in this specific situation I am only matching numbers, so a /\d*/ would do. I am trying to understand a general rule so that I can apply it whenever.

Anybody would be so kind to help me out?

Answer

kennytm picture kennytm · Dec 21, 2011

How about the simpler

str.match(/[^%]*/i)[0]

Which means, match zero-or-more character, which is not a %.


Edit: If need to parse until </a>, then you could parse a sequence pf characters, followed by </a>, then then discard the </a>, which means you should use positive look-ahead instead of negative.

str.match(/.*?(?=<\/a>|$)/i)[0]

This means: match zero-or-more character lazily, until reaching a </a> or end of string.

Note that *? is a single operator, (.*)? is not the same as .*?.

(And don't parse HTML with a single regex, as usual.)