I want to locate a substring of numbers. This substring will begin with a period .
.
Example string: myString = 12v3i$#@.789v10vvi4e9k
should return 789
.
My (very hacky) solution:
.
I'm very new to regex (assuming that is the right tool here), how can this be done with regex?
console.log(/\.(\d+)/.exec("12v3i$#@.789v10vvi4e9k")[1]);
# 789
\\.
will match the .
character (since it has a special meaning in RegEx, we need to escape it with \\
), followed by 1 more digits \\d+
. We group only those numbers and get them in the output array with [1]
You can use
var match = myString.match(/\.(\d+)/);
This will return array, where the first element is the whole match, and the second element contains the value of the first capture group (ie the digits).
I hope the expression is pretty straightforward, but nevertheless:
\\.
matches a .
literally ( .
is a special character in expressions, so it has to be escaped) \\d+
matches one or more digits To learn about regular expressions: http://www.regular-expressions.info/tutorial.html
You can do this:
console.log("12v3i$#@.789v10vvi4e9k".match(/\.(\d+)/).pop());
\\.
matches literal .
and \\d+
matches on or more digits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.