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!

有帮助吗?

解决方案

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.

其他提示

  • \\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)([^:]*)(?:[:])
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top