What Regex will match from a specified "trigger" until a space?
I 开发者_如何学Gohave this regex /\[\w+:/
Which I use to let me detect when a user types [something:
into a text field (could be [place: , [info: , [user: , etc...).
I'd like to extend the regex to match characters after the :
but not beyond a space (and not include the space either). For example,
var str = "This is a [place:car a great place to go!";
var matchedStr = str.match(REGEX);
The matchedStr value should be [place:car
.
Thanks!
It depends on which chars you want to allow in the string after the ':'.
If you want to match anything except whitespace, the following should work:
/\[\w+:[^\s]*/
If you just want it to match letters, Lee's solution will work. If you want it to match letters, numbers & underscores, Joseph's answer will do that.
Also, do you want it to succeed if there are no non-space chars after the ':'?
If you want it to match "[aaaa:bbbb", but not "[aaaa:", then you should change the * to a +
/\[\w+:[^\s]+/
\S
matches anything that is not whitespace, so you could do \[\w+:\S+
to get your desired match. This includes not just regular space but newlines, tabs, etc too. (which is probably what you want)
You can also simply do a negative character class with a space in: \[\w+:[^ ]+
(which will include tabs/newlines/etc)
Demo
var str = "This is a [place:car a great place to go!";
var matchedStr = str.match(/\[\w+:\w*/);
That works
You want a zero-width negative lookahead assertion. See: http://www.regular-expressions.info/lookaround.html
/\[\w+:(?!\s)/
It asserts that the following text does not match its expression, but does not consume any of the input characters (zero-width).
this, maybe
var REGEX = /.*(\[[a-z]+:[a-z]+)\s.*/;
var str = "This is a [place:car a great place to go!";
var matchedStr = str.match(REGEX);
var result = matchedStr[1];
alert(result)
http://jsfiddle.net/konglie/ExzGz/
精彩评论