2012-01-16 63 views
0

我不是RegEx专家,我尽我所能与http://gskinner.com/RegExr/,但我找不到合适的解决方案。这里是我的问题:正则表达式:替换。与 - 在

我有一堆的HTML文件与ID,如

<span id="listing0.title.moreinfo">bla</span> 

还有其他的ID没有

<span id="listing0">bla</span> 

我的问题: 如何更换所有-?没有的ID。不应该改变。

我敢肯定,这不是最好的解决办法,但我这是怎么找到的所有ID:

/(id=")(([\w\d])*)(.*([\w\d])*)"/gi 
+1

您计划执行正则表达式的语言是什么? – Aphelion 2012-01-16 12:42:22

+0

我希望直接在Notepad ++或Eclipse中为所有HTML页面执行此操作。 – manuel 2012-01-16 12:56:42

+0

我用Eclipse,用$ 1 $ 2- $ 4替换(id =“)([\ w \ d - ] +)(\。)([\ w \ d \。] +”),运行了几次并完成。 – manuel 2012-01-16 14:56:06

回答

1

我这样做,在PHP,但过程是一样的。

// pattern to find all the ids 
$reg = '/id="([^"]+)"/'; 
$str = '<span id="listing0.title.moreinfo">bla</span>'; 
// find all the ids. second first subgroup will contain the id string. 
preg_match($reg, $str, $m); 

// replace . with - with simple string replace function. 
echo str_replace('/\./', '-', $m[0]); 

标准的ID字符串找到正则表达式将是/id="([^"]+)"/gi

+0

谢谢你的字符串发现正则表达式!但是有没有一种方法可以在不将字符串传递给变量的情况下替换点,只需要使用正则表达式? – manuel 2012-01-16 12:55:16

+0

我不认为它可能在像eclipse或notepad ++编辑器,除非有一个外部插件。 – 2012-01-16 16:15:30

0

这个工作在C#:

var html = @"<span id=""listing0.title.moreinfo"">bla</span> 
      <span id=""listing0"">bla</span>"; 

var pattern = @"id=("".*?"")"; 

html = Regex.Replace(html, pattern, delegate(Match match) 
            { 
             return match.Value.Replace('.', '-'); 
            }); 

Console.WriteLine(html); 
Console.ReadKey(); 
0

用记事本++,

  • 搜索:id="(\w+)\.(\w+)\.(\w+)"
  • 代之以:id="\1-\2-\3"