简体   繁体   English

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

[英]JavaScript regex: find non-numeric character

Let's say I have these two strings: "5/15/1983" and "1983.05.15". 假设我有这两个字符串:“5/15/1983”和“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. 字符串中任何给定的非数字字符的所有实例都是相同的。

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! 谢谢!

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

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

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 我希望你能得到答案

Clearly tired or not paying attention on my previous answer. 显然很累或没注意我以前的答案。 Sorry about that. 对于那个很抱歉。 What I should have 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. 当然,Matthew Flaschen的作品也同样如此。 I just wanted to correct mine. 我只是想纠正我的。

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

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