regex - Match Strings with Variable Left/Right Delimiters -


The problem is quite simple. At the beginning I want to match anything between some stars and between the stars in the end. In the end, the strings must initially match the appropriate strings .

Let's say I want to match everything between [ and ] or { and } .

The first regular expression that can be used:

/[{\[ }(.*)[} ​​elseother/gmu

However this is a problem. When the subject is:

{AT} Verifyiu [AB] wrewre [ac}

would also be [AC} But it should not be.

It can be easily changed by:

/ \ [(. *) \] | \ {(. *) \} / Gmu

And the problem is resolved.

But what if (. *) were more complex and examples for beginning and ending 10 and they would be a bit more complicated (not a character but many)? Then using the entire rule, the whole (. *) should be repeated twice and it will be unclear.

Is there any way to end the match with the beginning? For example, I want to use the same syntax as

/ (aa | bb) (. *) (Cc | ddd) / gmu to indicate that the match Should start with and cc end or starts with BB and ends with ddd And the subject in the match aaxx1cc bbxx2ddd aaxx3ddd bbxx4cc only the strings xx1 and xx2 without repeating (. *) that Many times in regular expressions and remember there can be more than 2 In the beginning and end of the above examples.

Use a conditional

In my opinion, to use this conditional It's a great place to work regex:

  (?: (\ [) | ({)). *? (? (1) \]) (? (2)})  < 

Other types of delimiter

It is easy to extend : For example, the following patterns between START and END or and - & gt; , or between ==: and : ==

  (? :( START) | (& lt; -) | (==:)). *? (? (1) END) (? (2) - & gt;) (? (3): ==)   

See .

Explanation

  • Non-occupation group (?: (\ [) | ())
  • >
  • Code>
  • { which moves ({} to group 2
  • . *? laziness matches a point where ...
  • (? (1) \]) If the group is set 1, then we match ]
  • ((2)}) if the group is 2 set, then we }

    < Strong> context



Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -