Simple regex. Get the number from [~21~]
I have a string that looks like this: [~21~]. How can I use regex to only return 21? The number can be any value (numbers), at any length. I am using Javascript with this regex, so if you coul开发者_StackOverflow社区d include that in your exsample, that would be great.
Thomas
You can:
- Remove any other characters than digits
- Parse the resulting number to a real number instead of a string
Like:
var number = parseInt(str.replace(/[\D]/g, ""), 10);
Where:
parseInt(..., 10)
parses any string to a number in base 10str.replace(..., "")
will remove characters (replace them with nothing)[\D]
means: anything except digits
For example,
parseInt("[~21~]".replace(/[\D]/g, ""), 10) === 21;
Note that it will concatenate numbers in e.g. [~21~22~]
; that will become 2122
.
A simple regex that will work in your case is:
[0-9]+
This will match a sequence of strings consisting of the characters: 0,1,2,3,4,5,6,7,8,9
If you aren't worried about error-handling:
var getTheNumber = function(a) { return a.substring(0, a.length-2).substring(2); }
-*\d+(\.\d+)*
Contemplates negative and/or decimal numbers. This will extract any number of 1 or more digits no matter the string.
精彩评论