有趣的问题。这可以在 JavaScript 中使用正则表达式和String.replace()
具有回调函数替换值的方法轻松解决。首先,需要制作一个正则表达式来匹配那些在尾数中连续三个零数字后具有非零数字的高精度浮点数。这是一个用 python 自由间距模式编写的带有注释的正则表达式:
匹配要截断的数字的正则表达式:
re_truncatablebleFloat = re.compile(r"""
# Match real/float number having form: 1.23450009012345678E+12
\b # Anchor to word boundary.
( # $1: Part to be preserved.
\d+\. # Integer portion and dot.
[1-9]* # Zero or more non-zero decimal digits.
(?: # Zero or more significant zeros.
0 # Allow a zero digit, but only
(?!00) # if not start of a triple 000.
[1-9]* # Zero or more non-zero decimal digits.
)* # Zero or more significant zeros.
000+ # Three or more zeros mark end of first part.
) # End $1: Part to be preserved.
([1-9]\d*) # $2: Mantissa digits to be zeroed out.
([Ee][+-]\d+) # $3: Well formed exponent.
\b # Anchor to word boundary.
""", re.VERBOSE)
请注意,此正则表达式仅匹配那些需要修改的浮点数。它捕获捕获组中数字的初始部分,组$1
中要归零的数字$2
,最后是组中的指数$3
。
用于修复文本的 JavaScript 函数:
以下是一个经过测试的 JavaScript 函数,它利用上述正则表达式和回调函数来解决手头的问题:
function processText(text) {
var re = /\b(\d+\.[1-9]*(?:0(?!00)[1-9]*)*000+)([1-9]\d*)([Ee][+-]\d+)\b/g;
return text.replace(re,
function(m0, m1, m2, m3){
m2 = m2.replace(/[1-9]/g, '0');
return m1 + m2 + m3;
});
}
单页独立Web应用解决方案:
以下是包含上述 JavaScript 功能的独立网页
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>Process Text 20140217_1300</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body {margin: 2em; color:#333; background:#DDB;}
h1, p {font-family: monospace; text-align: center;}
textarea {width: 99%;}
</style>
<script type="text/javascript">/* <![CDATA[ */
// Process the input text.
function processText(text) {
var re = /\b(\d+\.[1-9]*(?:0(?!00)[1-9]*)*000+)([1-9]\d*)([Ee][+-]\d+)\b/g;
return text.replace(re,
function(m0, m1, m2, m3){
m2 = m2.replace(/[1-9]/g, '0');
return m1 + m2 + m3;
});
}
/* Read input, process, then write to output */
function handleOnclick() {
var el_in = document.getElementById('inbox'),
el_out = document.getElementById('outbox');
el_out.value = processText(el_in.value);
return false;
} /* ]]> */</script>
</head><body>
<h1>Process Text</h1>
<form action="" method="get">
<h2>Input:</h2>
<p>
<textarea id="inbox" name="inbox" rows="10" cols="80"></textarea>
<input type="button" id="process" name="process" value="Process"
onclick="return handleOnclick();"/>
</p>
<h2>Output:</h2>
<p>
<textarea id="outbox" name="outbox" rows="10" cols="80"></textarea>
Note: Line endings may not be preserved! (i.e.
LF may be changed to CRLF or vice-verse)
</p>
</form>
</body></html>
只需将其保存为桌面上的 HTML 文件,然后使用您喜欢的浏览器打开即可。它不需要外部资源,并且可以轻松修改/重新用于解决类似问题。
快乐的正则表达式!