views:

153

answers:

1

Trying to match ONLY the first character in the sample below.

Sample string: C/C++/Objective C/Objective-C/ObjectiveC/objectiveC

My faulty regex: (?![O|o]bjective[ |-]?)C(?!\+\+)

Doh.

A: 

Try this:

(?<![Oo]bjective[ -]?)C(?!\+\+)


Corrections are:

  • Use negative lookbehind instead of negative lookahead (the (?<!...) bit).
  • Removed pipe character from character classes (the [...] bits).

It might also be worth adding a pair of \bs either side of the C, since your current regex will match Coconut, BBC, CFML and so on

Also worth pointing out that, inside character classes, the - is special if not the first or last character. Some people prefer to escape it even in these situations, i.e. [ \-], in case a later character is accidentally added after it.

Peter Boughton