Kosmetika
Kosmetika

Reputation: 21304

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!

Upvotes: 12

Views: 20340

Answers (4)

Jerry
Jerry

Reputation: 71548

You could use:

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

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

Upvotes: 14

David Hellsing
David Hellsing

Reputation: 108500

You can use match and count the resulting array:

str.match(/%/g).length == 1

Upvotes: 2

melwil
melwil

Reputation: 2553

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

Upvotes: 11

Niccolò Campolungo
Niccolò Campolungo

Reputation: 12042

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

Upvotes: 2

Related Questions