1

试图弄清楚如何将 % 附加到数字上。数字长度各不相同,所以这就是我不确定的......如何创建一个正则表达式,它接受任何数字并将 % 附加到它。

我在想这个,但你会如何处理意想不到的长度?

"\\%d{DigitlegnthVariesHere}"

还是像这样简单"\\%d"

4

1 回答 1

9

以下是如何在字符串中的%每个(整数)数字之后放置一个(编辑:请参见下面的小数)

//                              In the "search for" regular expression:
//             +--------------- \d means "any digit"
//             | +------------- +  means "one or more of the previous thing"
//             | | +----------- The 'g' flag means "globally" in the string
//             | | |            --------------------------
//             | | |            In the replacement string:
//             | | |   +------- $& means "the text that matched"
//             | | |   | +----- % isn't special here, it's just a literal % sign
//             | | |   | |
//             V V V   V V
s = s.replace(/\d+/g, "$&%");

例子:

var s = "testing 123 testing 456";
s = s.replace(/\d+/g, "$&%");
console.log(s); // "testing 123% testing 456%"

在下面的评论中,您说:

问题如果你输入像 47.56 这样的小数,它会输出 45% 56%

非常正确,因为\d仅用于数字,它不会神奇地包含..

处理小数需要稍微复杂一点的表达式:

//                                    In the "search for" regular expression:
//             +--------------------- \d means "any digit"
//             | +------------------- +  means "one or more of the previous thing"
//             | |+------------------ (?:....) is a non-capturing group (more below)
//             | ||  +--------------- \. is a literal "."
//             | ||  | +------------- \d means "any digit" again
//             | ||  | |   +--------- ? means "zero or one of the previous thing,"
//             | ||  | |   |          which in this case is the non-capturing group
//             | ||  | |   |          containing (or not) the dot plus more digits
//             | ||  | |   | +------- The 'g' flag means "globally" in the string
//             | ||  | |   | |        --------------------------
//             | ||  | |   | |        In the replacement string:
//             | ||  | |   | |   +--- $& means "the text that matched"
//             | ||  | |   | |   | +- % isn't special here, it's just a literal % sign
//             | ||  | |   | |   | |
//             V VV  V V   V V   V V
s = s.replace(/\d+(?:\.\d+)?/g, "$&%");

所以基本上说的是:匹配一系列数字,可选地后跟一个小数点和更多数字,并将它们替换为匹配的字符加上一个%.

例子:

var s = "testing 123.67 testing 456. And then...";
s = s.replace(/\d+(?:\.\d+)?/g, "$&%");
console.log(s); // "testing 123.67% testing 456%. And then..."

请注意,即使 the456后面跟着 a .,因为它后面没有更多的数字,我们也没有在 .%后面不恰当地添加 a .


有一次,您的问题是在数字“前面”而不是在数字后面。如果你真的想要它在数字前面,只需移动:%$&

str = str.replace(/\d+/g, "%$&");
于 2013-05-20T14:52:04.373 回答