2

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

and as @anubhava states, .* is "greedy" and not a good idea, because if you got two or more columns in your string, it may match only the last one.
That overly greedy operator was driving me crazy.
1
  • \\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)([^:]*)(?:[:])

1 Comment

My bad, the extra '\' was for escaping. Otherwise, string.match() still returns an array containing two entries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.