2009-02-28 78 views
0

我有一些nemerle代码如下方法:语法错误匹配链接的URL

private static getLinks(text : string) : array[string] { 
     def linkrx = Regex(@"<a\shref=['|\"](.*?)['|\"].*?>"); 
     def m = linkrx.Matches(text); 
     mutable txmatches : array[string]; 
     for (mutable i = 0; i < m.Count; ++i) { 
      txmatches[i] = m[i].Value; 
     } 
     txmatches 
    } 

问题是,编译器因某种原因被试图解析正则表达式语句及其括号内导致程序不能编译。如果我删除了@,(我被告知要放在那里)我得到一个无效的转义字符错误的“\ S”

继承人的编译器输出:

NCrawler.n:23:21:23:22: ←[01;31merror←[0m: when parsing this `(' brace group 
NCrawler.n:23:38:23:39: ←[01;31merror←[0m: unexpected closing bracket `]' 
NCrawler.n:22:57:22:58: ←[01;31merror←[0m: when parsing this `{' brace group 
NCrawler.n:23:38:23:39: ←[01;31merror←[0m: unexpected closing bracket `]' 
NCrawler.n:8:1:8:2: ←[01;31merror←[0m: when parsing this `{' brace group 
NCrawler.n:23:38:23:39: ←[01;31merror←[0m: unexpected closing bracket `]' 
NCrawler.n:23:38:23:39: ←[01;31merror←[0m: unexpected closing bracket `]' 

(第23行是行与正则表达式代码就可以了)

我该怎么办?

回答

3

我不知道Nemerle,但它似乎使用@禁用所有转义,包括"转义。

尝试其中之一:

def linkrx = Regex("<a\\shref=['\"](.*?)['\"].*?>"); 

def linkrx = Regex(@"<a\shref=['""](.*?)['""].*?>"); 

def linkrx = Regex(@"<a\shref=['\x22](.*?)['\x22].*?>"); 
+0

只是为了记录在案,该功能被称为“逐字字符串文字“。 – CMS 2009-02-28 06:44:13

1

的问题是带引号,没有括号。在Nemerle中,与C#中一样,用另一个引号将引号标出,而不是反斜杠。

@"<a\shref=['""](.*?)['""].*?>" 

编辑:请注意,你不需要在方括号内的管道;内容被视为一组字符(或字符范围),其中隐含有OR。

2

我不是Nemerle程序员,但我知道你应该总是使用XML解析器来处理基于XML的数据,而不是正则表达式。

我猜有人建立DOM或XPath库Nemerle这样你就可以访问任何

//一个[@href]通过XPath或类似的东西通过DOM a.href.value。

那当前的正则表达式不喜欢例如

<a class="foo" href="something">bar</a> 

我没有测试这一点,但它应该是更喜欢它

/<a\s.+?href=['|\"]([^'\">]+)['|\"].+?>/i 
+0

OP是否说他正在解析XML?我所看到的只是他将一个正则表达式应用于一些看起来像HTML定位标记的字符串。至于在'href'之前可能存在的其他属性,我会假设他知道这不会发生;毕竟,这是他的数据。 – 2009-02-28 06:49:57