简体   繁体   中英

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 .

My (very hacky) solution:

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

console.log(/\.(\d+)/.exec("12v3i$#@.789v10vvi4e9k")[1]);
# 789

RegEx Online Demo

正则表达式可视化

Debuggex Demo

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

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