Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match only if symbol in string used once

Maybe it's a simple question but today i'm a bit stucked with it.

I need regex to match only if symbol % appeared once in a string..

for example:

/regexpForSymbol(%)/.test('50%') => true
/regexpForSymbol(%)/.test('50%%') => false

Thanks!

like image 547
Kosmetika Avatar asked May 26 '13 18:05

Kosmetika


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you stop special characters in regex?

Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"


1 Answers

You could use:

^[^%]*%[^%]*$

The anchors are there to ensure every character is covered, and you probably already know what [^%] does.

like image 51
Jerry Avatar answered Oct 12 '22 11:10

Jerry