开发者

regex replacement that adds text

I'm trying to do link rewriting in my mobile application (written in ruby). I would like it to be able to accomplish both of these rewrites with a single regular expression:

m.example.com -> www.example.com
m.subd.example.com -> subd.example.com

The closest I've gotten replacing this:

m\.([a-z\.]*)example\.com

with this:

$1example.com

This works for the m.subd.example.com but it fails for m.example.com because of my "www." except开发者_运维问答ion.

I do this A LOT so i'd like it to be very fast, which is why I am trying to avoid using any code, just a single regex. Is it possible? Is there a fancy feature of regex that I don't know about?


I am trying to avoid using any code, just a single regex

Regex is code. A more complex regex takes longer to run. You'll need to write some code or run two regexes.

result = subject.gsub(/m\.([a-z.]*)example\.com/, '\1example.com').gsub(/^example\.com/, 'www.example.com')


I don't know Ruby, but here is a Perl script that does the job for the examples you've given. May be it could be translated.

#!/usr/local/bin/perl
use strict;
use warnings;

my @list = qw/m.example.com m.subd.example.com/;
my $re = qr#^m\.(.*)(example\.com)$#;
foreach(@list) {
  print $_;
  s/$re/($1 || "www.") . $2/e;
  print " -> $_ \n";
}

output:

m.example.com -> www.example.com 
m.subd.example.com -> subd.example.com 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜