当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Issue getting the shortest match using optional groups

问题描述:

I want to allow any 0 to 2 characters between each group in the (this is)?.??.??(an)?.??.??(example sentence) regex. It should match the bolded text in the below strings:

blah blah. An example sentence

blah blah. This is an example sentence

Something something Example sentence

Now, in the first example, the match is ah. example sentence. I thought adding 2 question marks to "." would mean that the regex engine will prefer to match 0 chars.

I'm using regex within VBA in MS Word, implemented by CreateObject("vbscript.regexp"), which as I understand it uses the VBScript regex flavor, which as I understand it is the same as the JavaScript flavor.

网友答案:

When searching 0020002101 should 2.??.??.??101 not prefer 2101 to 20002101?

Regex egine cannot "prefer" anything. It matches from left to right. Once the 2 is found (the first 2) it starts matching the subsequent subpatterns, and when a match is found, it is returned.

In your case, you need to use the .{0,2} inside the optional groups,

(this is.{0,2})?(an.{0,2})?(example sentence)
        ^^^^^^     ^^^^^^

See the regex demo.

If the order of the optional strings is important, make them nested:

(this is.{0,2}(an.{0,2})?)?(example sentence)

See another regex demo. This regex will only match an with 0 to 2 chars after it only if this is with 0 to 2 chars is found before it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: