仅当分隔符内还有换行符时,我才尝试捕获两个分隔符之间的文本。例如,如果我们有以下文本。
Organisation Name <<me.company.name>>
ABN/ACN <<me.company.abn>>
Contact Name <<me.name>>
<<me.PhoneNumber
Another line>>
Email <<me.emailAddress>>
我只想返回 <>
\n 可以是任何地方 - 基本上只匹配在 << 中至少有一个 \n 的匹配项>>>并忽略所有其他 << >>>
到目前为止我的模式是 <<(.?\n)*?>>>但这捕获了所有 << >>> (我正在使用 C#)
这是我尝试过的示例
https://regex101.com/r/sb0wCs/1
非常感谢您的帮助
I am trying to capture the text between 2 delimiters only when there is also a line feed within the delimiters. So for example if we have the following text.
Organisation Name <<me.company.name>>
ABN/ACN <<me.company.abn>>
Contact Name <<me.name>>
<<me.PhoneNumber
Another line>>
Email <<me.emailAddress>>
I am wanting to only return the <<me.PhoneNumber \n\n 'Another Line>>
the \n could be anywhere - basically only matches that have at least one \n within the << >> and ignore all other << >>
The pattern I have so far is <<(.?\n)*?>> but this captures all << >> (I'm using C#)
here is an example of what I have tried
https://regex101.com/r/sb0wCs/1
Thanks so much for your help
发布评论
评论(3)
您可以使用
regex demo 。 详细信息:
&lt;&lt;
- a&lt;&lt;&lt;
string((?:(? ;&gt;)。)*?\ n(?s:。)*?)
- 组1:(?:(?! ;&gt;
或&lt;&lt;
char序列,尽可能少\ n
- lf char(?s:。)*?
- 任何零或更多字符(包括newline chars),尽可能少&gt;&gt;
- a&gt;&gt; 字符串
You can use
See the regex demo. Details:
<<
- a<<
string((?:(?!<<|>>).)*?\n(?s:.)*?)
- Group 1:(?:(?!<<|>>).)*?
- any zero or more chars (other than newline chars) that do not start>>
or<<
char sequence, as few as possible\n
- a LF char(?s:.)*?
- any zero or more chars (including newline chars), as few as possible>>
- a>>
string在您的模式中
&lt;&lt;(。 *?
可以匹配,直到第一次出现&gt;&gt;
也可以在重复捕获组时,组值将保持最后一次迭代的值在您要捕获的整个部分周围没有量词的组。
如果您的字符串从行的开头开始,则可以使用锚点,并在其中至少匹配一条线,这不是从两者开始的。或&gt;&gt;
说明
^
字符串(
捕获组1。*
匹配该行的其余部分(?:\ r?\ n(?!&lt;&lt; |&gt;&gt;)。 >&lt;&lt;
或&gt;
\ r?\ n
匹配newline)
关闭组1\ s*&gt;&gt;
匹配可选的前导白板char和&gt;&gt;$
字符串的结尾请参见a regex demo 。
In your pattern
<<(.*?\n*)*?>>
you have a capture group and all parts are optional including the newline, so the non greedy quantifier*?
can match until the first occurrence of>>
Also when repeating a capture group, the group value will hold the value of the last iteration, so instead you can put the capture group without a quantifier around the whole part that you want to capture.
If your strings start at the beginning of the line, you can use anchors and match at least a single line in between that does not start with either << or >>
Explanation
^
Start of string\s*<<
Match optional leading whitspace chars and <<(
Capture group 1.*
Match the rest of the line(?:\r?\n(?!<<|>>).*)+
Match a newline, and repeat at least 1 line not starting with<<
or>>
\r?\n
Match a newline)
Close group 1\s*>>
Match optional leading whitspace chars and >>$
End of stringSee a regex demo.
您可以尝试一下:
&lt;&lt; [^&gt;]*?\ n [^&gt;]*&gt;&gt;&gt;
在此处进行测试: https://regex101.com/r/vd3ege/2
\ n
之间才能匹配A&lt;&lt;
和&gt;&gt;
。You can try this:
<<[^>]*?\n[^>]*>>
Test regex here: https://regex101.com/r/vD3EgE/2
\n
between<<
and>>
.