views:

50

answers:

4

I have this string:

sometext +[value]:-  

I would like to match the value(1-3 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.

+1  A: 

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.
codaddict
A: 

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...-.

Andreas Bonini
A: 

Try anchoring your match to the end of the string:

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

Hi guys! Thank you so much for your answers. Now I can keep working.

/martin

martin