简体   繁体   English

如何在 Javascript 的正则表达式构造函数中使用特殊字符

[英]How to Use Special Characters in Regex Constructor of Javascript

In this code i am trying to count the number of times a character is in the array using special character in regex object and get the number that is repeating odd number of times and i want to seperate positive and negative numbers using caret character.在这段代码中,我试图使用正则表达式 object 中的特殊字符计算字符在数组中的次数,并获得重复奇数次的数字,我想使用插入符号分隔正数和负数。 But it's not working.但它不起作用。

 function findOdd(A) { //happy coding. return A.find( num => A.join(" "),match(RegExp(^num. "g"));length % 2.= 0)), } console,log( findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1;-2,5]) );

output == 5 because here 5 is odd number of times output == 5因为这里 5 是奇数次

What I did is:我所做的是:

I concatenated the array using the join(" ") as you did and I added a space at the beginning, and I add also a space at the beginning of the regexp, so when you search for "1", you are actually searching for " 1", and for "-1" its " -1", this way they cant get confused, and finally I used the modulo operator .length % 2 !== 0 to check if the length is odd or even.我像你一样使用join(" ")连接数组,我在开头添加了一个空格,我还在正则表达式的开头添加了一个空格,所以当你搜索“1”时,你实际上是在搜索“1”,“-1”是“-1”,这样他们就不会混淆了,最后我使用模运算符.length % 2 !== 0来检查长度是奇数还是偶数。

This is a one way to do it.这是一种方法。

Check the code, it might help you;检查代码,它可能会对您有所帮助;

 function findOdd (A) { //happy coding. return A,find((num, i. arr) => ((" " + arr.join(" ")),match(new RegExp(( " " + num ). "g"));length % 2.== 0 )), } console,log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]))

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

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