regex - Coldfusion 替换函数或右函数返回一个空格
问题描述
我有这个功能,我需要获取 10 位数的电话号码。
<cffunction name="StandardPhoneNumber"
access="public"
hint="Returns a 10 digit phone number in a numeric format ex. 8883334444"
Description="We use a standard numeric only phone number. We stripped the non numeric characters and return 10 digit">
<cfargument name="phoneNumber" required="true" >
<!--- we need a little bit of processing here coz of a bug where a space is returned at the start of the number --->
<cfset local.phoneNumber = right(REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL"),10) />
<cfreturn trim(local.phoneNumber)/>
</cffunction>
由于某种原因,返回的值也返回了一些空间。
示例输入值“+5122131151”将返回“5122131151”(5 前面的空格)
添加了替换功能
REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL")
这样它即使带有破折号+1888-333-4444也可以接受电话号码并返回10位电话号码。这仅适用于标准电话号码为 10 位的美国电话号码。
解决方案
首先:不,你的功能不是罪魁祸首。正则表达式[^0-9]
去除所有非数字,包括空格。trim
函数末尾的 是多余的,甚至不需要。这是一个小提琴来证明它。 如果链接失效,请看最后的附件
当+
成为空格(空格字符)时,它更有可能与编码问题有关。当文字字符出现在 GET 查询字符串或 POST 有效负载中时,它会+
被替换为空格(更多详细信息)。因此,我认为您的输入/输出链中有问题,与功能无关。
另外,我不是美国电话号码以及如何正确处理国家电话代码的专家,但你的方法似乎有点太天真了。例如:如果电话号码少于 10 位,您将保留1
国家代码的+1
,因为right(number, 10)
仍然包含它。当您必须处理国际号码时,情况会更糟,因为国家/地区的呼叫代码可能不止一个数字并且有特殊规则(例如+49
,对于德国,0
如果存在,则去掉后面的 )。您可能需要考虑这一点。
无论如何,请检查您调用的位置StandardPhoneNumber()
,检查您通过的结果的结果,并检查您最终输出的内容。罪魁祸首隐藏在这个链条的某个地方。
附件
<cfset valuesToTest = [
"1234567890",
"123-4567-890",
"+1234567890",
"+123-4567-890",
"123",
"12345678901234567890",
" 1234567890#chr(9)#"
]>
<cfoutput>
<cfloop array="#valuesToTest#" index="value">
<cfset newValue = StandardPhoneNumber(value)>
#value# = #newValue# (length: #len(newValue)#)<br>
</cfloop>
</cfoutput>
<cffunction name="StandardPhoneNumber"
access="public"
hint="Returns a 10 digit phone number in a numeric format ex. 8883334444"
Description="We use a standard numeric only phone number. We stripped the non numeric characters and return 10 digit">
<cfargument name="phoneNumber" required="true">
<cfset local.phoneNumber = right(REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL"), 10)>
<cfreturn local.phoneNumber>
</cffunction>
推荐阅读
- r - 列的数据显示为“x,y” - 我如何将其绘制成散点图?
- angular - 如何使用 Typescript 2.8.x 使用 Angular CLI 6 进行构建
- sql - ORA-01427: 尝试使用 group by 子句更新时,单行子查询返回多行
- python - 将数据写入多索引熊猫数据框
- c# - 在c#中检查用户是否存在于活动目录组中的最快方法
- javascript - 将路径字符串从 unc 转换为 uri,在 Google Apps 脚本中将斜杠替换为反斜杠
- python - 为什么要在 multiprocessing.pool 之前定义 pool.map 的功能?
- vba - 单独导出 VBA 程序(子/函数)
- apache-kafka - 分区计数覆盖
- plsql - 将 Oracle Apex 中的数据加载表用于我有权访问的表