2012-09-12 51 views
0

我使用以下代码更新robots.txt,具体取决于特定页面是标记为允许还是禁止。ColdFusion从文本文件中删除空白行

<cflock type="exclusive" timeout="5"> 
    <cfset vRemoveLine = ListContainsNoCase(robots,"Disallow: #sURL#", "#chr(13)##chr(10)#")> 
    <cfif vRemoveLine> 
     <cfset robots = ListDeleteAt(robots, vRemoveLine, "#chr(13)##chr(10)#")> 
    </cfif> 
    <cffile action="write" 
     file="#sitePath#robots.txt" 
     output="#robots#" 
     nameconflict="overwrite"> 
</cflock> 

但是,它没有完成和/或可以写得更好。具体来说,删除一条线时,它也不会摆脱其关联的回车,如果该线位于底部右侧以外的任何位置,则更是如此。

屏幕截图:

1)之前除去线

enter image description here

2)除去线

enter image description here

还请注意在底部的额外空行之后。除了删除disallow和它的换行符之外,我需要删除所有这些空行。

+1

[装饰](http://cfdocs.org/trim)? –

+0

如果空行结束,则有效,但有时它们位于中间。还想知道是否有方法从文本文档中的任何位置删除整个空白行。 – user460114

回答

2

其实,更注重你的代码,你可以简单地做......

<cfset robots = robots.replaceAll("(?m)^Disallow: #ReEscape(sURL)#(?:\r?\n|\z)" , "") /> 

...而不是那些列表功能。

这将删除刚刚删除的行的换行符,但不会删除文件中其他任何地方存在的换行符(可能用于拆分节并提高可读性)。

如果您想确保文件末尾没有空白,您当然也可以使用trim。

通过解释,这里是上述正则表达式再次,在扩展/评论形式:

(?x) ## enable extended/comment mode 
     ## (literal whitespace is ignored, hashes start comments, also ignored) 
(?m) ## enable multiline mode 
     ## (meaning^and $ match start/end of each line, as well as of entire input) 

^Disallow:\ ## Match literal text "Disallow: " at start of a line. 
      ## (In comment mode, a \ is needed before the space 
      ## in standard use this is not required.) 

#ReEscape(sURL)# ## use ReEscape to avoid issues since the URL might 
        ## contain characters that are non-literal in a regex. 

(?:  ## non-capturing group to contain alternation between... 

    \r?\n ## match optional carriage return followed by a newline. 
|  ## or 
    \z  ## match end of input (whether there is a newline there or not) 
) 

(要使用在CFML,在这两个cfsavecontent和CFOUTPUT包起来,然后把得到的变量。里面robot.replaceAll(here,'')


如果你真的想保证不会有文件在多个换行符(不管)相关删除禁止线的任何变化,最简单的方法是:

<cfset robots = robots.trim().replaceAll('\r','').replaceAll('\n{2,}','\n') /> 

它修剪两端,然后删除所有回车符,然后用一个换行符替换至少两个换行符的所有实例。

(但总的来说,我可能会建议在毯子去除多个新行的初始更具体的表达。)

+0

真棒,非常感谢彼得:-) – user460114