Domanda

I am matching a string in Javascript against the following regex:

(?:new\s)(.*)(?:[:])

The string I use the function on is "new Tag:var;" What it suppod to return is only "Tag" but instead it returns an array containing "new Tag:" and the desired result as well.

I found out that I might need to use a lookbehind instead but since it is not supported in Javascript I am a bit lost.

Thank you in advance!

È stato utile?

Soluzione

Well, I don't really get why you make such a complicated regexp for what you want to extract:

(?:new\\s)(.*)(?:[:])

whereas it can be solved using the following:

s = "new Tag:";
var out = s.replace(/new\s([^:]*):.*;/, "$1")

where you got only one capturing group which is the one you're looking for.

Altri suggerimenti

  • \\s (double escaping) is only needed for creating RegExp instance.
  • Also your regex is using greedy pattern in .* which may be matching more than desired.

Make it non-greedy:

(?:new\s)(.*?)(?:[:])

OR better use negation:

(?:new\s)([^:]*)(?:[:])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top