search()发出未捕获的SyntaxError:无效的正则表达式:/*/:没什么可重复的

时间:2022-02-26 20:25:25

Can anyone explain this bug for me , what we have here is :

有人能给我解释一下这个bug吗?

if(statements[bracket].firsthalf.search(math_operators[j])!=-1)

where statements[bracket].firsthalf = "2*a" , math_operators[j]="*" , the console shows the following error:

语句(支架)。首先,控制台显示如下错误:

Uncaught SyntaxError: Invalid regular expression: /*/: Nothing to repeat

未被捕获的SyntaxError:无效的正则表达式:/*/:不需要重复

any idea why would it show such error ?

知道为什么会出现这样的错误吗?

search()发出未捕获的SyntaxError:无效的正则表达式:/*/:没什么可重复的

2 个解决方案

#1


11  

Use indexOf, not search. indexOf looks for literal strings, search is for matching a regular expression. In regular expressions, most punctuation characters have special meanings and need to be escaped if you want to find them literally, which is why you're getting errors.

使用indexOf,而不是搜索。indexOf查找字面字符串,搜索是为了匹配正则表达式。在正则表达式中,大多数标点符号都有特殊的含义,如果你想从字面上找到它们,就需要转义,这就是为什么你会出错。

#2


0  

Search need a RegularExpression as argument.

搜索需要一个正则表达式作为参数。

* is used to say 0 or more of the previous expression.

*用于表示前一个表达式的0或更多。

Like [0-9]* = 0 or more digits.

比如[0-9]* = 0或更多的数字。

To use * as a character you have to escape it :

要使用*作为一个角色,你必须要避开它:

\*

You have to write the search part as a regular expression.

你必须把搜索部分写成正则表达式。

2*a".search(*) is non sense, because it doesn't search the character (*) but 0 or more time nothing because there is nothing before the *.

2*a“.search(*)”是没有意义的,因为它不搜索字符(*),而是0或更多的时候什么都没有,因为在*之前什么都没有。

It's the same thing for the + that is protected character too.

同样的道理也适用于受保护字符的+。

You should use another function than search or write your request in a RegularExpression compliant manner like :

您应该使用另一个函数,而不是以符合正则表达式的方式搜索或编写请求:

search([\*|\+|\-|\/])

#1


11  

Use indexOf, not search. indexOf looks for literal strings, search is for matching a regular expression. In regular expressions, most punctuation characters have special meanings and need to be escaped if you want to find them literally, which is why you're getting errors.

使用indexOf,而不是搜索。indexOf查找字面字符串,搜索是为了匹配正则表达式。在正则表达式中,大多数标点符号都有特殊的含义,如果你想从字面上找到它们,就需要转义,这就是为什么你会出错。

#2


0  

Search need a RegularExpression as argument.

搜索需要一个正则表达式作为参数。

* is used to say 0 or more of the previous expression.

*用于表示前一个表达式的0或更多。

Like [0-9]* = 0 or more digits.

比如[0-9]* = 0或更多的数字。

To use * as a character you have to escape it :

要使用*作为一个角色,你必须要避开它:

\*

You have to write the search part as a regular expression.

你必须把搜索部分写成正则表达式。

2*a".search(*) is non sense, because it doesn't search the character (*) but 0 or more time nothing because there is nothing before the *.

2*a“.search(*)”是没有意义的,因为它不搜索字符(*),而是0或更多的时候什么都没有,因为在*之前什么都没有。

It's the same thing for the + that is protected character too.

同样的道理也适用于受保护字符的+。

You should use another function than search or write your request in a RegularExpression compliant manner like :

您应该使用另一个函数,而不是以符合正则表达式的方式搜索或编写请求:

search([\*|\+|\-|\/])