[英]Regular Expression To Match a Text Inside : -
I'm building a project that needs to match a text that is inside : text to match -
.我正在构建一个需要匹配内部
: text to match -
。 For example, if I have this string:例如,如果我有这个字符串:
nathanpc/ltweet: Asking a question at #StackOverflow: "Regular Expression To Match a Text Inside: -" - @devs
nathanpc/ltweet:在#StackOverflow 上提问:“正则表达式匹配内部文本:-”-@devs
I want to match Asking a question at #StackOverflow: "Regular Expression To Match a Text Inside: -"
.我想匹配
Asking a question at #StackOverflow: "Regular Expression To Match a Text Inside: -"
。 Everything that is after the first :
and the last -
, but what is the correct regular expression to do this?第一个
:
和最后一个-
之后的所有内容,但是正确的正则表达式是什么?
PS: I'm using Javascript with jQuery PS:我正在使用 Javascript 和 jQuery
If you're using Perl-compatible regular expressions, like those found in most languages:如果您使用与 Perl 兼容的正则表达式,例如大多数语言中的正则表达式:
/:(.*)-/
You might not need the slashes, depending on the language.您可能不需要斜杠,具体取决于语言。 The capture group 1 will get the content you want.
捕获组 1 将获得您想要的内容。
The .*
is a greedy matcher, so it will attempt to match as many characters as possible, up to the last dash in the input. .*
是一个贪心匹配器,因此它将尝试匹配尽可能多的字符,直到输入中的最后一个破折号。
If you use a greedy operator like .
如果您使用像
.
it will try to form the largest match possible (at least in Perl compatible regular expression engines)它将尝试形成最大的匹配(至少在 Perl 兼容的正则表达式引擎中)
So to match this something as simple as :(.*)-
will work.所以要匹配这个像
:(.*)-
这样简单的东西就可以了。
See this example script in Perl:请参阅 Perl 中的示例脚本:
my $str = "Discard:Testing:- one two three -discard";
$str =~ m/:(.*)-/;
print $1;
$1 = "Testing:- one two three"
Or in javascript here: http://www.regular-expressions.info/javascriptexample.html或在 javascript 中: http://www.regular-expressions.info/javascriptexample.html
This works for me (ruby):这对我有用(红宝石):
[^:]+:\s+([^-]+.*?)\s-
Test:测试:
test = "nathanpc/ltweet: Asking a question at #StackOverflow: 'Regular Expression To Match a Text Inside : -' - @devs"
m = test.match /[^:]+:\s+([^-]+.*?)\s-/
then然后
m[1].to_s
produces生产
Asking a question at #StackOverflow: 'Regular Expression To Match a Text Inside : -'
As others have noticed the much simpler :(.*)-
works the same.正如其他人所注意到的那样,更简单的
:(.*)-
工作方式相同。 Perhaps without spaces :\s(.*)\s-
也许没有空格
:\s(.*)\s-
"Standard" regular expressions cannot parse this text exactly as you described. “标准”正则表达式无法完全按照您的描述解析此文本。 That parsing requires some context , that cannot be expressed with regexes.
该解析需要一些不能用正则表达式表达的上下文。 For example, when receiving the first "-", how does the expression not to end?
比如收到第一个“-”时,表达式怎么不结束呢?
Out of my head, I can only come with Perl extended regular expressions, that allow sub-expression parsing, but it won't be easy, as you have to count the occurrences of ":" and "-" to match exactly the last one.在我的脑海中,我只能使用 Perl 扩展正则表达式,它允许子表达式解析,但这并不容易,因为你必须计算“:”和“-”的出现次数才能完全匹配最后一个一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.