简体   繁体   English

正则表达式查找数字,然后精确匹配字符串

[英]Regex to find number followed by exact string match

I've got a string. 我有绳子。 Let's say "This response happened in 90ms. Response finished". 假设“此响应发生在90毫秒内。响应完成”。

I need to be able to parse out the "90ms" from the string. 我需要能够从字符串中解析出“ 90ms”。

The regex needs to match against an arbitrary number of numbers followed by an exact string match, in this case the string would be "ms". 正则表达式需要与任意数量的数字进行匹配,然后再进行精确的字符串匹配,在这种情况下,字符串将是“ ms”。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Why don't you try this regex? 您为什么不尝试此正则表达式?

\d+ms

\\d+ - matches one or more digits. \\d+ -匹配一个或多个数字。

ms - Matches the string ms ms匹配字符串ms

Example: 例:

> "This response happened in 90ms. Response finished".match(/\d+ms/)[0];
'90ms'

Use this regexp: 使用此正则表达式:

\d+ms

\\d matches a digit, + means to match 1 or more of them, and ms matches that exact string. \\d匹配一个数字, +表示匹配1个或多个, ms匹配那个确切的字符串。

Now I suggest you go read a tutorial on regular expressions, there's one at regular-expressions.info. 现在,我建议您阅读有关正则表达式的教程,regular-expressions.info中有一个。 This is about as basic as it gets, so if you need to ask about things like this you'll be here every day, getting us to write your code one line at a time. 这几乎是最基本的,因此,如果您需要询问类似这样的事情,您每天都会在这里,使我们一次只编写一行代码。

To extract the expression you need to use this: 要提取表达式,您需要使用以下命令:

var rx = /(\d+ms)/;
var arr = rx.exec(your_string);
extracted= arr[1];

The extracted string is what is between parenthesis. 提取的字符串是括号之间的内容。 If you need only the number change de rx to /(\\d+)ms/. 如果只需要数字,请将de rx更改为/(\\ d +)ms /。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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