Last active
December 29, 2015 05:29
-
-
Save zhasm/7622481 to your computer and use it in GitHub Desktop.
parse 99 只含有数字的参数,数值可能从 -99 到 99 之间变换,如何用正则匹配到整个字符串,从而完成在字符串末尾加上一个“度”字呢
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
#所需的函数: | |
p_99, 使用js 内置的parseInt,做比较; | |
或 | |
re_99,使用正则式做匹配测试。 | |
如果只想匹配 2 位的数字,忽略1位的数字,将 [0-9]{1,2} 改为 [0-9]{2} 即可。 | |
### | |
p_99 = (degree) -> | |
if -99 <= parseInt(degree) <= 99 | |
return degree + '度' | |
'' | |
re_99 = (degree) -> | |
if "#{degree}".match(///^\s*-?[0-9]{1,2}\s*$///) | |
return degree + '度' | |
'' | |
### | |
#测试过程 | |
### | |
for i in [-200, -100, -99, -50, 0, 50, 99, 100, 200, NaN, '任意字串'] | |
console.log "input: #{i}, p_99 return: #{p_99 i}" | |
console.log "input: #{i}, re_99 return: #{re_99 i}" | |
#测试结果 | |
input: -200, p_99 return: | |
input: -200, re_99 return: | |
input: -100, p_99 return: | |
input: -100, re_99 return: | |
input: -99, p_99 return: -99度 | |
input: -99, re_99 return: -99度 | |
input: -50, p_99 return: -50度 | |
input: -50, re_99 return: -50度 | |
input: 0, p_99 return: 0度 | |
input: 0, re_99 return: 0度 | |
input: 50, p_99 return: 50度 | |
input: 50, re_99 return: 50度 | |
input: 99, p_99 return: 99度 | |
input: 99, re_99 return: 99度 | |
input: 100, p_99 return: | |
input: 100, re_99 return: | |
input: 200, p_99 return: | |
input: 200, re_99 return: | |
input: NaN, p_99 return: | |
input: NaN, re_99 return: | |
input: 任意字串, p_99 return: | |
input: 任意字串, re_99 return: | |
#对应 javascript | |
/* | |
#所需的函数: | |
p_99, 使用js 内置的parseInt,做比较; | |
或 | |
re_99,使用正则式做匹配测试。 | |
如果只想匹配 2 位的数字,忽略1位的数字,将 [0-9]{1,2} 改为 [0-9]{2} 即可。 | |
*/ | |
var i, p_99, re_99, _i, _len, _ref; | |
p_99 = function(degree) { | |
var _ref; | |
if ((-99 <= (_ref = parseInt(degree)) && _ref <= 99)) { | |
return degree + '度'; | |
} | |
return ''; | |
}; | |
re_99 = function(degree) { | |
if (("" + degree).match(/^\s*-?[0-9]{1,2}\s*$/)) { | |
return degree + '度'; | |
} | |
return ''; | |
}; | |
/* | |
#测试过程 | |
*/ | |
_ref = [-200, -100, -99, -50, 0, 50, 99, 100, 200, NaN, '任意字串']; | |
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | |
i = _ref[_i]; | |
console.log("input: " + i + ", p_99 return: " + (p_99(i))); | |
console.log("input: " + i + ", re_99 return: " + (re_99(i))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment