[英]Regex in JS: find a string of numbers that are preceded by a character
I want to locate a substring of numbers. 我想找到一个数字子串。 This substring will begin with a period
.
该子字符串将以句点开头
.
. 。
Example string: myString = 12v3i$#@.789v10vvi4e9k
should return 789
. 示例字符串:
myString = 12v3i$#@.789v10vvi4e9k
应该返回789
。
My (very hacky) solution: 我的(非常hacky)解决方案:
.
.
I'm very new to regex (assuming that is the right tool here), how can this be done with regex? 我是regex的新手(假设这里是正确的工具),那么如何用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+
. 字符(由于它在RegEx中具有特殊含义,我们需要使用
\\
对其进行转义),然后再加上1个数字\\d+
。 We group only those numbers and get them in the output array with [1]
我们仅对这些数字进行分组,并使用
[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 \\d+
匹配一个或多个数字 To learn about regular expressions: http://www.regular-expressions.info/tutorial.html 要了解正则表达式: 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. 和
\\d+
匹配一个或多个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.