简体   繁体   English

匹配可选的捕获组

[英]Matching an Optional Capture Group

I want to match an xml element and create a group for an optional attribute. 我想匹配一个xml元素,并为可选属性创建一个组。 If the attribute does not exist then i'm going to perform some other action. 如果属性不存在,那么我将执行其他操作。 For example i have 例如我有

<customer display="no">

I want to match on the customer element but the display attribute might not exist. 我想在客户元素上进行匹配,但显示属性可能不存在。 In code i was going to check to see if that capture group is empty and if so perform some custom logic. 在代码中,我将检查该捕获组是否为空,如果是,请执行一些自定义逻辑。

so the regex i have is 所以我有的正则表达式是

<customer.*(display="yes|no").*?>

That matches the element ok when it has the attribute but how can i make the group optional so i can check to see if the element was included? 当它具有属性时,它与元素ok匹配,但是如何使该组可选,以便我可以检查是否包含该元素?

You can just put a question mark after the group, the same as any other optional component of a regex. 您可以在组后面加上问号,就像正则表达式的其他任何可选组件一样。 You will also have to make the first .* lazy (by adding ? ) if you do this, otherwise it will consume the whole line. 如果这样做,您还必须使第一个.*惰性(通过添加? ),否则它将消耗整行。

So you should have something like this: 所以你应该有这样的东西:

<customer.*?(display="yes|no")?.*?>

Also note that (display="yes|no") probably doesn't match what you want it to: it matches display="yes or no" not display="yes" or display="no" . 还要注意(display="yes|no")可能与您想要的不匹配:它匹配display="yesno" not display="yes"display="no" I suspect you want (display="(?:yes|no)") instead. 我怀疑您想要(display="(?:yes|no)")代替。

Try this regex: 试试这个正则表达式:

<customer.*?(display="(?:yes|no)").*?>

explain: 说明:

?

Matches the previous element zero or one time. 匹配上一个元素零或一次。

*?

Matches the previous element zero or more times, but as few times as possible. 与上一个元素匹配零次或多次,但次数最少。

(?: subexpression)

Defines a noncapturing group. 定义一个非捕获组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM