开发者

regex. How can I match the value between '+' and ':'?

I have this string:

sometext +[value]:-  

I would like to match the value(1-3开发者_StackOverflow numerical characters) (with regex, javascript)

sometext may contain a +sign if i'm unlucky so I don't wanna end up with matching

some +text +value:-

I sat up last night banging my head against this, so I would be really glad if someone could help me.


If sometext contains a + but not numbers you can use the regex:

\+\d{1,3}:-
  • \+: + is a meta char, to match a literal + we need to escape it as \+
  • \d: short for [0-9], to represent a single digit
  • {1,3}: quantifier with min=1 and max=3, so \d{1,3} matches a number with 1, 2 and 3 digits
  • : : to match a colon
  • - : to match a hyphen, its not a meta char outside a char class...so need no escape.


Try anchoring your match to the end of the string:

/\+(\d{1,3}):-$/


Edit

If like you said in the post body (but unlike you said in the post title) you need to match sometext +[value]:-:

var result = "sometext +[value]:-".match(/\+\[(.*)\]\:-/i)

Result:

result[0] = "+[value]:-"
result[1] = "value"

Old answer

"some +text +value:-".match(/\+.*-/i)

The result is +text +value:-. It will match everything in +...here...-.


Get (multiple) values as array:

var input = "some +text +value:- +another_value:-";
input.match(/(?!\+)(\w+)(?=:-)/g) // ["value", "another_value"]

Or get the string if only one value is expected:

var input = "some +text +value:-";
input.match(/(?!\+)(\w+)(?=:-)/g)[0] // "value"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜