这个问题看起来微不足道-但事实并非如此。我想使用regexp从字符串中删除所有非数字字符,但不包含第一个#
字符。您可以使用下面的代码段(并在其中编辑magic
函数)进行测试:
function magic(str) {
// example hardcoded implementation - remove it and use proper regexp
return str.replace(/#1234a5678b910/,'#12345678910');
}
// Test
tests = { // keys is input string, value is valid result for that input
"#1234a5678b910": "#12345678910",
"12#34a5678b910": "12#345678910",
"1234a56#78b910": "123456#78910",
"1234a5678b91#0": "1234567891#0",
"1234a5678b91#0": "1234567891#0",
"98#765a4321#039c": "98#7654321039",
"98a765#4321#039c": "98765#4321039",
"98a765b4321###39": "987654321#39",
}
Object.keys(tests).map(k=> console.log(`${k} Test: ${(''+(magic(k)==tests[k])).padEnd(5,' ').toUpperCase()} ( result is ${magic(k)} - should be ${tests[k]})`) );
输入字符串以随机方式生成。到目前为止,我尝试了这个,但是没有运气
function magic(str) {
return str.replace(/(?<=#.*)[^0-9]/g, '') ;
}
热衷于使用replace和regexp吗?
答案 0 :(得分:2)
可变长度回溯仅适用于某些JavaScript引擎(EMCA2018)。请参阅浏览器兼容性,了解后置断言here。
对于支持后向搜索的引擎,可以使用以下正则表达式:
(?<!^[^#]*(?=#))\D+
工作原理如下:
(?<!^[^#]*(?=#))
后面的否定性确保以下内容不匹配
^
在字符串开头声明位置[^#]*
与#
以外的任何字符匹配任意次数(?=#)
积极的前瞻性,确保随后#
\D+
匹配任何非数字字符一次或多次简而言之,^[^#]*(?=#)
匹配到遇到第一个#
的位置。然后,我们对这些结果求反(因为我们不想替换每个字符串中的第一个#
)。最后,我们匹配与这些位置不匹配的非数字字符\D+
。
function magic(str) {
// example hardcoded implementation - remove it and use proper regexp
return str.replace(/(?<!^[^#]*(?=#))\D+/g,'');
}
// Test
tests = { // keys is input string, value is valid result for that input
"#1234a5678b910": "#12345678910",
"12#34a5678b910": "12#345678910",
"1234a56#78b910": "123456#78910",
"1234a5678b91#0": "1234567891#0",
"1234a5678b91#0": "1234567891#0",
"98#765a4321#039c": "98#7654321039",
"98a765#4321#039c": "98765#4321039",
"98a765b4321###39": "987654321#39",
}
Object.keys(tests).map(k=> console.log(`${k} Test: ${(''+(magic(k)==tests[k])).padEnd(5,' ').toUpperCase()} ( result is ${magic(k)} - should be ${tests[k]})`) );
此方法最适合跨浏览器支持(较旧的浏览器或当前不支持EMCA2018的浏览器)。
这使用两个正则表达式清除两个子字符串:
[^\d#]+ # replace all characters that aren't digits or # (first substring)
\D+ # replace all non-digit characters (second substring)
function magic(str) {
// example hardcoded implementation - remove it and use proper regexp
i = str.indexOf('#') || 0
x = str.substr(0,i+1)
y = str.substr(i+1)
r = x.replace(/[^\d#]+/g,'')+y.replace(/\D+/g,'')
//console.log([i,x,y,r])
return r
}
// Test
tests = { // keys is input string, value is valid result for that input
"#1234a5678b910": "#12345678910",
"12#34a5678b910": "12#345678910",
"1234a56#78b910": "123456#78910",
"1234a5678b91#0": "1234567891#0",
"1234a5678b91#0": "1234567891#0",
"98#765a4321#039c": "98#7654321039",
"98a765#4321#039c": "98765#4321039",
"98a765b4321###39": "987654321#39",
}
Object.keys(tests).map(k=> console.log(`${k} Test: ${(''+(magic(k)==tests[k])).padEnd(5,' ').toUpperCase()} ( result is ${magic(k)} - should be ${tests[k]})`) );
答案 1 :(得分:2)
非常简单-匹配包括第一个mytime
(如果有)的部分,只需替换第二个组中的非数字即可。然后,将它们粘在一起。
#
答案 2 :(得分:0)
使用此正则表达式替换字符串([a-zA-Z])|(?<=#(.*?))#
。这将匹配a-z
以及A-Z
和#
中的所有字符,后跟另一个#和字母。