Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape asterisk in regexp?

I want to use the pattern *1*. I have tried \*1\*, but it doesn't work. Where is the problem?

like image 710
user2080105 Avatar asked Mar 04 '13 15:03

user2080105


People also ask

What does * do in regex?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.

How do you match an asterisk in regex?

Resolution. To use 'regexp' syntax, you must use a / (slash) at the beginning and end of the regexp. To wildcard text at the beginning and ending of the line, add a ". *" (dot asterisk) to the beginning and end of the 'Actor Command Line'.

Does asterisk need to be escaped?

In all other cases, the asterisk is treated as a literal asterisk. While you do not need to escape asterisks everywhere in project files, doing so does no harm.

What characters have to be escaped regex?

Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.


1 Answers

You have to escape it with a backslash:

/\*1\*/ 

Otherwise, an unescaped * in a RegExp will mean: Match 0 or more of the Preceding Character Group.

Update:

If you use the RegExp constructor, do it this way:

new RegExp("\\*1\\*") 

You have to double-escape the backslashes because they need to be escaped in the string itself.

like image 190
Beat Richartz Avatar answered Sep 25 '22 09:09

Beat Richartz