简体   繁体   English

正则表达式字符串零或更多

[英]Regex String zero or more

I have follow Regex: 我遵循正则表达式:

(.*?)( EUR)\1*

and on String 2 mm; EUR 和弦2 mm; EUR 2 mm; EUR it matches 2mm; 2 mm; EUR ,匹配2mm; and EUR but the String 2 mm; EUR但字符串2 mm; matches nothing!? 什么都不匹配!

But why ? 但为什么 ? I thought the * meant zero or more times? 我以为*表示零次或多次? Can you help me? 你能帮助我吗? Thank you! 谢谢!

It would have been a better approach to tell what result you want. 告诉您想要什么结果,将是更好的方法。

If you want a Regex to match "2 mm; EUR" or "2 mm;", it implies that you want to match a string starting with some kind of number (might be a millimiter length? something like that), ending with a ";" 如果要让正则表达式匹配“ 2毫米; EUR”或“ 2毫米;”,则表示您要匹配以某种数字开头的字符串(可能是毫米长度?类似这样),以a结尾“;” and eventually followed by the string " EUR". 最后是字符串“EUR”。

If it is what you want, your regex should have a ";" 如果它是你想要的,你的正则表达式应该有一个“;” inside and mark EUR with a "?" 在里面用欧元标记“?” (0 or 1) (0或1)

([\n]+ .*?);( EUR)?

The following regex will match both cases, 2 mm; EUR 以下正则表达式将匹配两种情况( 2 mm; EUR 2 mm; EUR as well as 2 mm; 2 mm; EUR以及2 mm;

(.*?;\s)(EUR)|(.*;)

Example

Yes you are right * means 'zero or more times'. 是的,您是对的*表示“零次或多次”。 What you don't seem to understand is \\1 . 您似乎不了解\\1 It means 'the content captured by the first caturing group. 它的意思是“第一个访问组捕获的内容。

Your regular expression (.*?)( EUR)\\1* means therefore: 您的正则表达式(.*?)( EUR)\\1*表示:

any string, followed by the four letters EUR (with a space), followed by zero or more times the start of the string. 任何字符串,后跟四个字母EUR (带空格),后跟零或多次字符串开头。

If the string is 2 mm; EUR2 mm;2 mm; 如果弦是2 mm; EUR2 mm;2 mm; 2 mm; EUR2 mm;2 mm; , (.*?) will match 2 mm; (.*?)将匹配2 mm; , ( EUR) will match EUR , and \\1* will match 2 mm;2 mm; ( EUR)将匹配EUR ,并且\\1*将匹配2 mm;2 mm; .

Now that you understand your error, you will find more easily the correct expression. 既然您已经理解了错误,那么您将更容易找到正确的表达方式。 Just remove \\1 . 只需删除\\1

(.*?)( EUR)*

will match anything, followed be zero or more times EUR . 将匹配任何内容,后跟零或更多倍EUR

^(.*?)( EUR.*)?$

will match anything before ' EUR', or the whole string if it is missing. 将匹配'EUR'之前的任何内容,或者如果缺少则匹配整个字符串。 Notice that we added the start and end marks to make sure the whole string is captured when there is no EUR. 请注意,我们添加了开始和结束标记,以确保在没有EUR时捕获整个字符串。

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

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