-1

What is the regex to ensure a string is in below pattern

string::string with | as the separator if more than one.

For example:

1::String (ok)

1::James is a boy|2::Hello (ok)

1:James is a boy | 2:Hello (not ok - single column)

1:String , 2:Hellos (not ok - separator is a comma)

I tried the following code:

$pattern = '/\w::\w|/'; $string = "1::Strings|1::Strings"; preg_match($pattern , $string, $match);
user1502826
  • 395
  • 4
  • 12
  • $pattern = '/\w::\w|/'; $string = "1::Strings|1::Strings"; preg_match($pattern , $string, $match); How to enforce the separator if more than one is the challenge – user1502826 Jan 18 '16 at 15:26

1 Answers1

1

You could try a regex like this

^(?:(\w+::\w[^:]+)\|)*(?1)$
  • (\w+::\w[^:]+) the subpattern is the format defined inside the first capture group.
  • ^(?:...\|)* any amount of subpattern inside non capture group with trailing |
  • (?1) subpattern is required at least once

See demo at regex101

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46