2012-09-12 45 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