JavaScript 正则表达式:查找非数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3411123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:31:40  来源:igfitidea点击:

JavaScript regex: find non-numeric character

javascriptregex

提问by JamesBrownIsDead

Let's say I have these two strings: "5/15/1983" and "1983.05.15". Assume that all characters in the string will be numeric, except a "separator" character that can appear anywhere in the string. There will be only one separator character; all instances of any given non-numeric character in the string will be identical.

假设我有这两个字符串:“5/15/1983”和“1983.05.15”。假设字符串中的所有字符都是数字,除了可以出现在字符串中任何位置的“分隔符”字符。将只有一个分隔符;字符串中任何给定非数字字符的所有实例都是相同的。

How can I use regex to extract this character? Is there a more efficient way than the one below?

如何使用正则表达式来提取这个字符?有没有比下面更有效的方法?

"05-15-1983".replace(/\d/g, "")[0];

Thanks!

谢谢!

回答by Matthew Flaschen

"05-15-1983".match(/\D/)

Technically, this returns an array containing one string, but it will implicitly convert to the string most places you need this.

从技术上讲,这将返回一个包含一个字符串的数组,但它会在您需要的大多数地方隐式转换为字符串。

回答by KoolKabin

Though i could not exactly get what you trying to do i tried to extract the numbers only in one string and the seperator in next string.

虽然我不能完全得到你想要做什么,但我试图只提取一个字符串中的数字和下一个字符串中的分隔符。

I used the above:

我使用了上面的:

<script>
var myStr1 = "1981-01-05";
var myStr2 = "1981-01-05";
var RegEx1 = /[0-9]/g;
var RegEx2 = /[^0-9]/g;
var RegEx3 = /[^0-9]/;
document.write( 'First : ' + myStr1.match( RegEx1 ) + '<br />' );
document.write( 'tooo : ' + myStr2.replace( RegEx2,  "" ) + '<br />' );
document.write( 'Second : ' + myStr1.match( RegEx2 ) + '<br />'  );
document.write( 'Third : ' + myStr1.match( RegEx3 ) + '<br />'  );
</script>

Output:

输出:

First : 1,9,8,1,0,1,0,5
tooo : 19810105
Second : -,-
Third : -

I hope you get your answer

我希望你得到你的答案

回答by eldarerathis

Clearly tired or not paying attention on my previous answer. Sorry about that. What I shouldhave written was:

显然累了或没有注意我之前的回答。对于那个很抱歉。我应该写的是:

var regexp = new RegExp("([^0-9])","g");
var separator = regexp.exec("1985-10-20")[1];

Of course, Matthew Flaschen's works just as well. I just wanted to correct mine.

当然,Matthew Flaschen 的作品也一样。我只是想纠正我的。