开发者

reverse regex lookup for particular string

开发者 https://www.devze.com 2023-02-02 13:15 出处:网络
\"very \\n simple example of big\" => return true because first occurrence moving backwards from example is \\n
"very \n simple example of big"
 => return true because first occurrence moving backwards from example is \n


"very \n\t\t simple example of big" 
 => return false because first occurrence moving backwards from example is \n\t\t

is this possible through reverse regex loo开发者_Python百科kup?


I'm not sure exactly what you're looking for but you can always reverse the string and match forward:

>> "very \n simple example of big".reverse.match(/elpmaxe[^\t]+\n/)
=> #<MatchData "elpmaxe elpmis \n">

>> "very \n\t\t simple example of big".reverse.match(/elpmaxe[^\t]+\n/)
=> nil

I'm not sure if this has crossed the line between clever and stupid but it works on your examples.


I'm still not entirely sure what you are looking for, but if it is "Find out whether or not the word 'example' occurs on a line that does not start with any tabs," then here you go:

ruby-1.9.2-p136 :001 > samples = [ "very \n simple example of big", "very \n\t\t simple example of big" ]
 => ["very \n simple example of big", "very \n\t\t simple example of big"] 
ruby-1.9.2-p136 :002 > samples.map{ |s| s[/^[^\t\n]+.+?example/] }
 => [" simple example", nil] 


I donno Ruby, hence giving the regex that I verified in Javascript:

/\n[^(\t+)]+ example/g


The question isn't too clear, but I think this is what you want, using a negative lookahead:

^(?!\t\t).*example

Example: http://rubular.com/r/DRdlscH6cO

Here I'm using ^ for start of the line (you can use \n if you prefer, but it wouldn't match the first line). . will not match another line by default, so it's also safe.
You may also want to add capturing groups, and match only a whole word:

^(?!\t\t)(.*)\bexample\b

The regex doesn't allow lines that contain example, and start with \t\t. The line can start with a single \t, or have \t\t elsewhere.

0

精彩评论

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

关注公众号