开发者

Replace end of line text but preserve newline character

EDIT Sorry I realized my question is a non-problem. Markdown consume开发者_StackOverflow社区d the newline character. Nonetheless my code still has problem and the answer gives the correct solution.

I am using Ruby, and I want to find ID numbers at end of some lines, convert it into a URL. For example

>253
irrelevant text
>254

to

> foo.php/253
irrelevant text
> foo.php/254

I tried something similar to the following, but the newlines/carriage returns get consumed.

text.gsub!(  /^(> ?)(\d+)(\s*$)/  ,  "\\1\\2\\3"  )

The result will all be in one line. I also does not know if it is going to be /r, /n or /r/n, so I don't want to hardcode the line break characters.


This should work:

text.gsub(/(?:^|(?<=[\r\n]))>[ \t]*(\d+)(?=\s*?(?:$|[\r\n]))/m, "> foo.php/\\1")

Example: http://ideone.com/fgAK7

Update: This one is better (and shorter):

/(?<![^\r\n])>[ \t]*(\d+)[ \t]*(?![^\r\n])/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜