Java 带有 = 和 ; 的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2274303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:33:27  来源:igfitidea点击:

Regular expression with an = and a ;

javaregexescaping

提问by chama

I'm trying to use a regular expression to find all substrings that start with an equals sign (=) and ends with a semicolon (;) with any number of characters in between. It should be something like this =*;

我正在尝试使用正则表达式来查找所有以等号 ( =)开头并以分号 ( ;)结尾且中间包含任意数量字符的子字符串。它应该是这样的=*;

For some reason, the equals is not registering. Is there some sort of escape character that will make the regex notice my equals sign?

出于某种原因,equals 没有注册。是否有某种转义字符会使正则表达式注意到我的等号?

I'm working in Java if that has any bearings on this question.

如果这对这个问题有任何影响,我正在使用 Java。

采纳答案by jjnguy

This may be what you are looking for. You need to specify a character set or wild card character that you are applying the asterisk to.

这可能就是您正在寻找的。您需要指定要应用星号的字符集或通配符。

"=([^;]*);"

You can also use the reluctant quantifier:

您还可以使用不情愿量词:

"=(.*?);"

Using the parenthesis you now have groups. I believe the first group is the whole entire match, and group[1]is the group found within the parenthesis.

使用括号,您现在有了组。我相信第一组是整场比赛,group[1]是括号内的组。

The code may look something like:

代码可能类似于:

Regex r = new Regex("=([^;]*);");
Match m = r.Match(yourData);
while (m.Success) {
    string match = m.Groups[1];
    // match should be the text between the '=' and the ';'.
}

回答by Jon Skeet

This looks for "any number of = signs, including 0"

这将查找“任意数量的 = 符号,包括 0”

=*;

If you want "= followed by any number of other characters" you want

如果您想要“= 后跟任意数量的其他字符”

=.*;

However, that will match greedily - if you want lazy matching (so that it stops one group when it finds the next semicolon) you might want:

但是,这将贪婪地匹配 - 如果您想要延迟匹配(以便在找到下一个分号时停止一个组),您可能需要:

=.*?;

回答by Marcel Hymanwerth

The regex you provided would match ;, ===;, ..., ================;. How about =.*;(or =.*?;if non-greedy is needed)?

您提供的正则表达式将匹配;, ===;, ..., ================;。怎么样=.*;(或者=.*?;如果需要非贪婪)?

回答by Martin Milan

Something like =.*;

像 =.*;

回答by crunchdog

An excellent source for learning about regexp in Java: sun's book about regexp

在 Java 中学习正则表达式的极好资源:sun 的关于正则表达式的书