匹配相同字符串的两个不同部分

时间:2022-09-13 13:29:57

I've got the following string:

我有以下字符串:

{!ex=track_created_f}track_created_f:[NOW/DAY-3MONTHS/DAY TO NOW/DAY]

{ !前女友= track_created_f } track_created_f:(现在/ DAY-3MONTHS /天/天)

I would like to match/extract track_created_f and NOW/DAY-3MONTHS/DAY TO NOW/DAY. The {!ex=track_created_f} might or might not be present at all times, so the regex should not rely on this part.

我想要把track_created_f和NOW/DAY-3月/DAY /DAY改为现在/天。{ !ex=track_created_f}可能在任何时候都不会出现,所以regex不应该依赖于这一部分。

However, it is the second track_created_f (and not the track_created_f which is a part of !ex=track_created_f) which I need to match.

但是,我需要匹配的是第二个track_created_f(而不是track_created_f,它是!ex=track_created_f的一部分)。

What I've got so far is the following (see this link for live preview):

到目前为止,我所得到的是以下内容(请参阅现场预览链接):

[^.*(\w+)\:\[(.*)?\]$]

However, this just gives me :

然而,这给了我:

Array
(
    [0] => {!ex=track_created_f}track_created_f:[NOW/DAY-3MONTHS/DAY TO NOW/DAY]
    [2] => f
    [2] => NOW/DAY-3MONTHS/DAY TO NOW/DAY
)

What I'm having trouble to get a real grip on is how I can use regex to match only the part(s) of the string which I'd like to match, and only return that part. As it is now, (0) the entire string is being returned along with (1) the not so good match of track_created_f and (2) the match of NOW/DAY-3MONTHS/DAY TO NOW/DAY.

我很难真正理解的是如何使用regex只匹配我想匹配的字符串的部分,并且只返回该部分。现在,(0)整个字符串与(1)track_created_f的不太匹配和(2)now /DAY- 3months /DAY到now /DAY的匹配一起返回。

I've been trying to figure this one out by reading the docs, but I'm uncertain as to whether I'm getting things right - particularly the optional '?' clauses I've put in. Is that the right way to match subsets of strings at all?

我一直试图通过阅读文档来解决这个问题,但我不确定我是否做对了事情——尤其是可选的。”“我加的条款。这是匹配字符串子集的正确方法吗?

2 个解决方案

#1


3  

[^.*(\w+)\:\[(.*)?\]$] is a wrong regex. You are actually putting whole regex inside a regex character class.

(^ . *(\ w +)\:\[(. *)?$]是错误的regex。实际上,您将整个regex放在regex字符类中。

The following regex is enough

下面的regex就足够了

/(\w+):\[([^\]]+)/

#2


0  

^(?:{\!ex=\w+}|)(.*):\[(.*)?\]$

That will make the {!ex=track_created_f} part optional.

这将使{!前女友= track_created_f }部分可选的。

See: http://www.phpliveregex.com/p/1gc

参见:http://www.phpliveregex.com/p/1gc

#1


3  

[^.*(\w+)\:\[(.*)?\]$] is a wrong regex. You are actually putting whole regex inside a regex character class.

(^ . *(\ w +)\:\[(. *)?$]是错误的regex。实际上,您将整个regex放在regex字符类中。

The following regex is enough

下面的regex就足够了

/(\w+):\[([^\]]+)/

#2


0  

^(?:{\!ex=\w+}|)(.*):\[(.*)?\]$

That will make the {!ex=track_created_f} part optional.

这将使{!前女友= track_created_f }部分可选的。

See: http://www.phpliveregex.com/p/1gc

参见:http://www.phpliveregex.com/p/1gc