-1

I'm looking for a regular expression that character # and ## only can occur once in a literal string.

It should match:

a#abc
a#bc##e
a##bc#e
a##e

But it should be non-compliant about:

a#a#b#c
a##bc##e
a##bc##e##d
a###e
Thomas Ayoub
  • 27,208
  • 15
  • 85
  • 130
Henry Chen
  • 41
  • 4

1 Answers1

2

You could use the following regex, composed of an alternation of these two patterns:

  1. ## is matched, then a single # may appear

  2. a single # is matched, then ## may appear

^[^#]*(?:##[^#]*#?|#[^#]*(?:##)?)[^#]*$

If the regex should match strings without any #, just make the whole alternation optional :

^[^#]*(?:##[^#]*#?|#[^#]*(?:##)?)?[^#]*$
Toby Speight
  • 23,550
  • 47
  • 57
  • 84
Aaron
  • 21,986
  • 2
  • 27
  • 48
  • Good point, Thank you for your attention! here I want to supplement the filter condition. If the literal string is `null` or `#` and `##` don't occur once in this string, it also should be compliant. It should also match: – Henry Chen Mar 01 '17 at 10:19
  • @HenryChen the second regex I provided should work fine then, it can match empty strings and strings that contain no `#` – Aaron Mar 01 '17 at 10:31
  • Yes, it do make sense. Thank you again! I will adopt this idea. – Henry Chen Mar 01 '17 at 11:24