It doesn't seem like the regex pattern was right

I need to check a string for a specific string, I want to use a regular expression for this, but the more I try, the more it bothers me (and upsets); I don't seem to understand.

I need the expression to return true when the string contains something like this: [[module:instance]] , but it must satisfy the following conditions:

  • Always open with two brackets [[
  • After two brackets, a string can contain everything except : and has no length restrictions for it
  • After character 1 : must be a character
  • After : again a line that can contain everything except : and has no length limit
  • Always close with 2 brackets ]]

Any help, advice, good tutorials, something would be very helpful!

Thanks in advance!

+4
source share
5 answers

Try the following:

 preg_match('/\[\[[^:]+?:[^:]+?]]/', $str, $match) 

Explanation:

  • \[\[ matches literal [[
  • [^:]+? matches any except : (not greedy)
  • : matches literal :
  • [^:]+? matches any except : (not greedy)
  • ]] matches the literal ]] .
+6
source
 \[\[[^:]+:[^:]+\]\] 

Explanation:

\[\[ matches two opening brackets.

[^:] matches any single character except for the colon.

[^:]+ matches one or more characters except colons.

+2
source

Try this for your regex:

 \[\[.*?:[^:]*?\]\] 

Backslashes are required before square brackets because they are metacharacters such as., *, And ?.

+1
source

What about \[\[[^:]+\:[^:]+\]\] ? It works?

It must match two literal characters [ , then any character that is not : repeats at least once, then a : and then any character that is not : at least once, then two literals ] .

0
source

Will this work?

[[[^]: {1} [^:]]]

0
source

Source: https://habr.com/ru/post/1334991/


All Articles