10

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!

Kosmetika
  • 20,774
  • 37
  • 108
  • 172

4 Answers4

12

You could use:

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

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

Jerry
  • 70,495
  • 13
  • 100
  • 144
  • You should use PCRE negation(!) , ^[!%}*%[!%]*$. Thanks. – Frank Aug 08 '16 at 13:00
  • @Frank That is not a valid syntax. – Jerry Nov 16 '16 at 09:48
  • i don't know for example. put a full explanation when you answer – mangusta May 01 '23 at 19:32
  • @mangusta I don't know... the expression is pretty simple if someone took the time to read the basics of regular expressions... `^` matches the start of string, `[^...]` is a negated class, `*` is a quantifier, and `$` matches the end of the string. The `%` is literal. – Jerry May 31 '23 at 06:34
10

Here you go. Don't expect everyone to make these for you all the time though.

^      # Start of string
[^%]*  # Any number of a character not matching `%`, including none.
%      # Matching exactly one `%`
[^%]*  # 
$      # End of string
melwil
  • 2,547
  • 1
  • 19
  • 34
  • 5
    That downvote was unnecessary. I'll gladly delete it if it's a duplicate. Just because it's a duplicate doesn't make it wrong in any way. – melwil May 26 '13 at 18:47
  • @Kosmetika I've explained the regex for you. This is pretty basic regex. If you like to use regex you should read up on it a bit. – melwil May 26 '13 at 18:51
1

You don't need regex.

function checkIfOne(string, char) {
    return string.split(char).length === 2;
}

Usage:

var myString = "abcde%fgh",
    check = checkIfOne(myString, '%'); // will be true
Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
1

You can use match and count the resulting array:

str.match(/%/g).length == 1
David Hellsing
  • 106,495
  • 44
  • 176
  • 212