多次匹配任何字符,但在给定字符处停止 [英] Match any characters more than once, but stop at a given character

查看:32
本文介绍了多次匹配任何字符,但在给定字符处停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个正则表达式,用于识别字符串中的命令.我有三个可能的命令开头的单词,它们总是以分号结尾.

I am writing a regex that will be used for recognizing commands in a string. I have three possible words the commands could start with and they always end with a semi-colon.

我相信正则表达式应该是这样的:

I believe the regex pattern should look something like this:

(command1|command2|command3).+;

我发现的问题是,由于 . 匹配任何字符并且 + 告诉它匹配一个或多个,它会直接跳过 a 的第一个实例分号并继续.

The problem, I have found, is that since . matches any character and + tells it to match one or more, it skips right over the first instance of a semi-colon and continues going.

有没有办法让它在遇到分号的第一个实例处停止?除了 . 之外,还有什么我应该使用的东西吗?

Is there a way to get it to stop at the first instance of a semi-colon it comes across? Is there something other than . that I should be using instead?

推荐答案

您面临的问题是:(command1|command2|command3).+;+ 是贪婪的,这意味着它将匹配所有内容,直到最后一个值.

The issue you are facing with this: (command1|command2|command3).+; is that the + is greedy, meaning that it will match everything till the last value.

要解决此问题,您需要使其不贪婪,为此您需要添加 ? 运算符,如下所示:(command1|command2|command3).+?;

To fix this, you will need to make it non-greedy, and to do that you need to add the ? operator, like so: (command1|command2|command3).+?;

正如仅供参考,这同样适用于 * 运算符.添加一个 ? 将使它不贪婪.

Just as an FYI, the same applies for the * operator. Adding a ? will make it non greedy.

这篇关于多次匹配任何字符,但在给定字符处停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆