regex 如何使用JavaScript在字符串中查找数字?

2vuwiymt  于 2022-12-19  发布在  Java
关注(0)|答案(9)|浏览(145)

假设我有一个字符串-“you can enter maximum 500 choices”,我需要从这个字符串中提取500
主要的问题是字符串可能会像“你可以输入最多12500个选择”一样变化。那么如何获得整数部分呢?

t9eec4r0

t9eec4r01#

使用regular expression

var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));

表达式\d+表示“一个或多个数字”。正则表达式默认为greedy,表示它们将尽可能多地获取。此外,还有:

var r = /\d+/;

相当于:

var r = new RegExp("\d+");

请参见details for the RegExp object
上面的代码将获取第一个组数字。你也可以循环查找所有匹配项:

var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

g(全局)标志是此循环工作的关键。

njthzxwz

njthzxwz2#

var regex = /\d+/g;
var string = "you can enter maximum 500 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches);
    • 参考资料:**

regular-expressions.info/javascript.htmlarchive
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExparchive

jgwigjjp

jgwigjjp3#

const str = "you can enter maximum 500 choices";
const result = str.replace(/[^0-9]/g, "");
console.log(result); // "500"

Playground:https://regex101.com/r/1ADa3c/1

fzsnzjdm

fzsnzjdm4#

我喜欢@jesterjunk回答,然而,数字并不总是数字。考虑那些有效的数字:“123.5、123,567.789、12233234+第12款”
所以我更新了正则表达式:

var regex = /[\d|,|.|e|E|\+]+/g;

var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches); //5,123.6
brtdzjyr

brtdzjyr5#

我想我应该加上我的看法,因为我只对第一个整数感兴趣,我把它归结为:

let errorStringWithNumbers = "error: 404 (not found)";        
let errorNumber = parseInt(errorStringWithNumbers.toString().match(/\d+/g)[0]);

.toString()仅在从获取错误中获取“string”时添加。如果没有,则可以将其从行中删除。

nr9pn0ug

nr9pn0ug6#

var regex = /\d+/g;
var string = "you can enter 30%-20% maximum 500 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches);
fivyi3re

fivyi3re7#

你也可以试试这个:

var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);
console.log(numbers)
t0ybt7op

t0ybt7op8#

// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

输出将为15
如果你想了解更多关于regex这里有一些链接:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

aydmsdu9

aydmsdu99#

现在,使用***'replace'方法和'regexp'***很容易做到。

findNumber = str => {
  return +(str.replace(/\D+/g, ''));
}

console.log(findNumber("you can enter maximum 500 choices"));
console.log(findNumber("you can enter maximum 12500 choices"));

相关问题