开发者

Regexp, how to limit a match

开发者 https://www.devze.com 2023-03-11 22:12 出处:网络
I have a string: string = %q{<span class=\"no\">2503</span>read_attribute_before_type_cast(<span class=\"pc\">self</span>.class.primary_key)}

I have a string:

string = %q{<span class="no">2503</span>read_attribute_before_type_cast(<span class="pc">self</span>.class.primary_key)}

In this example I want to match the words 'class' which are not in the tag. Regexp for this:

/\bclass[^=]/

But the problem is that it matches the last letter

/\bclass[^=]/.match(string) => 'clas开发者_JS百科s.'

I don't want have a last dot in a result. I've tried this regexp:

/\bclass(?:[^=])/

but still got the same result. How to limit the result to 'class'? Thanks


You are almost correct, but you have an error in your look ahead. Try this:

/\bclass(?!=)/

The regex term (?!=) means the input to the right must not match the character '='


You can take your variable string and extract a subsection using groups:

substring = string[/\b(class)[^=]/, 1]

The brackets around class will set that as the first "group", which is referred to by the 1 as the second parameter in the square brackets.


Assuming your only issue is keeping it from matching span.class.blah, just ignore . as well, so [^=.].

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号