[英]How can I capture the contents of one or more strings using a regex?
Let's say I have the following three strings: 假设我有以下三个字符串:
(section1){stuff could be any character, i want to grab it all} (第1节){东西可以是任何字符,我想全部抓住}
(section1)(section2){stuff could be any character, i want to grab it all} (section1)(section2){东西可以是任何字符,我想全部抓住}
(section1)(section2)(section3){stuff could be any character, i want to grab it all} (section1)(section2)(section3){东西可以是任何字符,我想全部抓住}
So if applied regex to my expressions, for the first I would get: 因此,如果将正则表达式应用于我的表达式,那么我首先会得到:
section1 SECTION1
stuff could be any character, i want to grab it all 东西可以是任何角色,我想抓住一切
if applied regex to my expressions, for the second I would get: 如果将正则表达式应用于我的表达式,第二秒钟我将得到:
section1 SECTION1
section2 第2节
stuff could be any character, i want to grab it all 东西可以是任何角色,我想抓住一切
and if applied regex to my expressions, for the third I would get: 如果将正则表达式应用到我的表达式中,那么第三次我将得到:
section1 SECTION1
section2 第2节
section3 SECTION3
stuff could be any character, i want to grab it all 东西可以是任何角色,我想抓住一切
I have the following regex: 我有以下正则表达式:
((?<section>.+))+{?<term>.+} ((?<节>。+))+ {<?术语>。+}
So look for inside parens and repeat and then what's inside the curly brackets. 因此,查找内部括号并重复,然后在大括号内查找内容。 It doesn't seem to work Any clue?
它似乎没有用任何线索? This has always been my Achille's heel.
这一直是我的致命弱点。
(?<section>\(.+?\))+?(?<term>\{.+\})
is probably closer to what you're looking for. 可能更接近您想要的东西。
This will match however many (section N ) segments you have, along with the {term} 无论您有多少段(第N部分),它都将与{term}相匹配
I didn't understand what you wanted very well, but I'll try to answer anyway 我不太了解您想要什么,但无论如何我都会尽力回答
(\(section1\)(\(section2\)(\(section3\))?)?)(.*)
That will match (and capture) (section1) followed by something else (or nothing) and optionally followed by a (section2) that could, in turn, be optionally followed by (section3) 这将匹配(并捕获)(第1节),然后再匹配其他内容(或什么都没有),然后可选地再跟上一个(第2节),然后又可以选择后跟(第3节)
I'm almost certain this isn't what you need, but at least will prompt you to describe your question better :-) 我几乎可以肯定这不是您所需要的,但至少会提示您更好地描述您的问题:-)
one thing to keep in mind as well when writing your regex, the occurance braces {} contain numbers, not wild cards. 编写正则表达式时要记住的一件事是,大括号{}包含数字,而不是通配符。
<regex>{3} //will match three exactly
<regex>{0,3} // will match up to and including three
<regex>{3,} // will match three or more
it is also nice to have a utility to test your strings out while trying to compose your pattern. 在尝试编写模式时,有一个实用程序可以测试您的字符串,这也很好。 here is one such online tool
这是一个这样的在线工具
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.