简体   繁体   English

JS中的正则表达式:查找一串以字符开头的数字

[英]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)解决方案:

  1. Find location of the period . 查找期间的位置.
  2. loop through each character that is next in string, if it is in [0-9], then add it to a string I'm building. 遍历字符串中下一个字符,如果它在[0-9]中,则将其添加到我正在构建的字符串中。 If not, break the loop. 如果没有,请打破循环。

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

RegEx Online Demo RegEx在线演示

正则表达式可视化

Debuggex Demo Debuggex演示

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM