开发者

regular expression gsub only if it does not have anything before

Is there anyway to scan only if there is nothing before what I am scanning for.

For example I have a post and I am scanning for a forward slash and what follows it but I do not want to scan for a forward slash if it is not the beginning character.

I want to scan for /this but I do not want to scan for this/this or http://this.com.

The regula开发者_Go百科r expression I am currently using is..

/\/(\w+)/

I am using this with gsub to link each /forwardslash.


I think what you are asking for is to only match words that begin with '/', not strings or lines beginning with '/'. If that is true, I believe the following regex will work: %r{(?:^|\s+)/(\w+)}:

For example:

"/foo /this this/that http://this".scan %r{(?:^|\s+)/(\w+)}  # => [["foo"], ["this"]]


The caret (^) character means "beginning of string" -- a dollar sign ($) means "end of string."
So

/^\/(\w+)/

...will get you what you want -- only matching at the beginning of the string.


First thing, since you're using a regex with slashes change the delimiter to something else, then you won't have to escape the backslashes and it will be easier to read.

Secondly, if you want to replace the slash as well then include it in the capture.

On to the regex.

...if it is not the beginning character...

...of a line:

!^(/\w+)!

if it is not the beginning character...

...of a word:

!\s(/\w+)!

but that won't match if it's at the very beginning of a line. For that you'll need something a lot more complex, so I'd just run both the regexes here instead of creating that monster.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜