Gordo
Gordo

Reputation: 789

Matching only a non repeated occurrence of a character with Javascript regexp

I am trying to match the asterisk character * but only when it occurs once.

I have tried:

/\*(?!\*)/g

Which checks ahead to see if the next character is not an asterisk. This gets me close, but I need to ensure that the previous character is also not an asterisk. Unfortunately javascript does not support negative lookbehind.

To clarify:

This is an ex*am*ple

should match each asterisk, but:

This is an ex**am**ple

should not return any match at all.

Thanks in advance

Upvotes: 1

Views: 182

Answers (1)

OrangeDog
OrangeDog

Reputation: 38777

var r = /(^|[^*])(\*)([^*]|$)/;

r.test('This is an ex*am*ple');    // true
r.test('This is an ex**am**ple');  // false
r.test('*This is an example');     // true
r.test('This is an example*');     // true
r.test('*');                       // true
r.test('**');                      // false

In all cases, the matched asterisk is in capture group 2.

For a complete solution, not using regular expressions:

function findAllSingleChar(str, chr) {
   var matches = [], ii;

   for (ii = 0; ii < str.length; ii++) {
     if (str[ii-1] !== chr && str[ii] === chr && str[ii+1] !== chr) {
       matches.push(ii);
     }
   }

   return matches.length ? matches : false;
}

findAllSingleChar('This is an ex*am*ple', '*');   // [13, 16]
findAllSingleChar('This is an ex**am**ple', '*'); // false
findAllSingleChar('*This is an example', '*');    // [0]
findAllSingleChar('This is an example*', '*');    // [18]
findAllSingleChar('*', '*');                      // [0]
findAllSingleChar('**', '*');                     // false

Upvotes: 3

Related Questions