是可能的ColdFusion的验证定界符



我的CF应用程序提供了三个选择(semicolon,comma或tab),以便用户选择匹配文件中的定界符。我想验证用户在文件中使用哪些定界符选择的内容。有办法这样做吗?

因此,如果用户正在为其文本文件使用选项卡定界符,但他不小心选择了一个逗号,那么我会得到此错误:

无效列表索引2。
在函数 ListGetAt(list, index [, delimiters])中,索引的值为2的值无效,因为第一个参数(此列表具有1个元素)。有效的索引在列表中的元素数量1到范围1。

我认为,避免这种错误的唯一方法是我是否可以验证用户的定界符正在文件中使用,但是当我搜索网络时我找不到任何示例。

您没有指定文件中哪种数据,因此这只是一个非常简单的猜测方法:

<!--- read file into memory --->
<cfset fileContent = fileRead( expandPath("yourfile.csv") )>
<!--- declare delimiting characters to check, NOTE: due to using "listLen" you may only specify single characters --->
<cfset possibleDelimiters = [ ";", ",", chr(9) ]> <!--- chr(9) = tab --->
<!--- count number of records found for each delimiter --->
<cfset countResults = {}>
<cfloop array="#possibleDelimiters#" index="delimiter">
    <cfset countResults[delimiter] = listLen(fileContent, delimiter)>
</cfloop>
<!--- determine delimiter with the highest count --->
<cfset sortedDelimiters = structSort(countResults, "NUMERIC", "DESC")>
<cfset mostFrequentDelimiter = sortedDelimiters[1]>
<cfoutput>
    Is <code>#encodeForHtml(mostFrequentDelimiter)# (#asc(mostFrequentDelimiter)#)</code> the delimiter?
</cfoutput>

但是,由于大多数书面语言的逗号频率,如果您在文件中有文本段落,这将非常猜测,因此请与一粒盐一起服用。

最新更新