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,095
  • 37
  • 101
  • 164

4 Answers4

12

You could use:

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

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

Jerry
  • 68,613
  • 12
  • 97
  • 138
9

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,508
  • 1
  • 18
  • 31
  • 4
    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,350
  • 3
  • 32
  • 38
1

You can use match and count the resulting array:

str.match(/%/g).length == 1
David Hellsing
  • 102,045
  • 43
  • 170
  • 208