1

I'm trying to match ABC from *ABC*, but not from **ABC**.

I've this so far;

/[^\*]{1}\*([^\*]+)\*[^\*]+/

The strings to match can be any of the following.

ABC **Don't match this** DEF
ABC *Match this* DEF
*Match this*
**Don't match this**

Linus Oleander
  • 17,181
  • 13
  • 67
  • 99

3 Answers3

6

You could use negative look-behind, negative look-ahead. That is

(?<!\*)\*ABC\*(?!\*)

Which reads out as

*ABC* not preceeded by *, and not succeeded by *.

aioobe
  • 399,198
  • 105
  • 792
  • 807
  • 2
    Or if the flavor does not support lookbehinds (like JavaScript) adding this at the beginning might suffice as well: `(?!.*\*{2})`. – Felix Kling Oct 29 '11 at 14:14
  • 1
    Or `\s\*ABC\*\s` if you can assure `*Match this*` will always be preceded and followed by a space. – Ben Oct 29 '11 at 14:15
  • 1
    @Felix - that lookahead will fail the regex if any `**` is in the string (`' *ABC* **'` will fail). –  Oct 29 '11 at 17:43
  • @sin: I know, that's why I said it *might* suffice ;) It clearly depends on the possible input. – Felix Kling Oct 29 '11 at 19:45
1

Your on the right track.
Without assertions: /(?:^|[^*])\*[^*]+*(?:[^*]|$)/
(use aioobe's regex with assertions, or any combination with/without).

0

if the string starts and ends with "*" you could use this:

/^*([^*]+)*$/

David
  • 4,514
  • 2
  • 32
  • 39