javascript正则表达式匹配工作但替换不起作用

时间:2017-04-19 19:51:33

标签: javascript regex

我正在尝试使用正则表达式取代我的正则表达式。当我使用match方法时,它返回具有正确索引和匹配的数组,但是当我使用replace并添加替换字符串时,它将无法工作。

["#,##0.00", index: 1, input: "$#,##0.00"]

返回var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+",""); console.log(b);

$#,##0.00

返回$,而我希望它只返回var a = "$#,##0.00".match("[\\d+-,#;()\\.]+"); console.log(a); var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+",""); console.log(b);

有人可以指出我做错了什么吗?谢谢 链接到示例是:

rst:
    sphinx-apidoc -M -f -e -o source/ ../mymodule


fullhtml:   rst html

1 个答案:

答案 0 :(得分:3)

.match只接受正则表达式。因此,如果提供了字符串 static int[] Shuffle(int[] a) { Random rnd = new Random(); //Remove duplicates from array int[] distinct = a.Distinct().ToArray(); //Add the same amount of unique numbers that have been removed as duplicates int len = a.Length - distinct.Length; int[] newNumbers = new int[len]; int i = 0; while(i < len) { newNumbers[i] = rnd.Next(a.Length); //NOTE: here i put in the length of array a, but with an int array this will always resolve in a shuffled array containing all digits from 0 to the length-1 of the array. if (!distinct.Contains(newNumbers[i]) && !newNumbers.Take(i).Contains(newNumbers[i])) { ++i; } } //Randomize the array int[] b = a.OrderBy(x => rnd.Next()).ToArray(); //Concatenate the two arrays and return it (shuffled numbers and new unique numbers) return distinct.Concat(newNumbers).ToArray(); } ,则会使用.match将其显式转换为正则表达式。

然而,

.replace接受一个字符串(字面意思是搜索)或正则表达式,如果你想让它使用正则表达式,你必须传入一个正则表达式。

new RegExp

或使用正则表达式文字:

var b = "$#,##0.00".replace(new RegExp("[\\d+-,#;()\\.]+"), "");
//                          ^^^^^^^^^^^                  ^