[英]JavaScript match ( followed by a digit
In string n+n(n+n)
, where n
stands for any number or digit, I'd like to match (
and replace it by *(
, but only if it is followed by a number or digit. 在字符串
n+n(n+n)
,其中n
代表任何数字或数字,我想进行匹配(
并将其替换为*(
,但前提是它后面跟随数字或数字。
Examples: 例子:
2+22(2+2)
into 2+22*(2+2)
, 2+22(2+2)
更改为2+22*(2+2)
, -1(3)
into -1*(3)
, -1(3)
更改为-1*(3)
, 4+(5/6)
should stay as it is. 4+(5/6)
应该保持原样。 This is what I have: 这就是我所拥有的:
var str = '2+2(2+2)'.replace(/^[0-9]\(/g, '*(');
But it doesn't work. 但这是行不通的。 Thanks in advance.
提前致谢。
Remove the ^
, and group the digits: 删除
^
,然后将数字分组:
'2+2(2+2)'.replace(/([0-9])\(/g, '$1*(')
'2+2(2+2)'.replace(/(\d)\(/g, '$1*(') //Another option: [0-9] = \d
Suggestion : 2.
is often a valid number (= 2
). 建议 :
2.
通常是有效数字(= 2
)。 The following RegExp removes a dot between a number and a parenthesis. 下面的RegExp删除数字和括号之间的点。
'2+2(2+2)'.replace(/(\d\).?\(/g, '$1*(') //2.(2+2) = 2*(2+2)
Parentheses create a group, which can be referenced using $n
, where n is the index of the group: $1
. 括号创建一个组,可使用
$n
进行引用,其中n是组的索引: $1
。
You started your RegExp with a ^...
, which means: Match a part of the string which starts with ...
. 您以
^...
开头了RegExp,这意味着:匹配以...
开头的字符串的一部分。 This behaviour was certainly not intended. 这种行为当然不是故意的。
var str = '2+2(2+2)+3(1+2)+2(-1/2)'.replace(/([0-9])\(/g, '$1*(');
http://jsfiddle.net/ZXU4Y/3/ http://jsfiddle.net/ZXU4Y/3/
This follows what you wrote (the bracket must follow a number). 这跟您所写的一样(括号内必须跟数字)。
So 4(
will be changed to 4*(
it could be important for example for 4(-1/2)
因此
4(
将更改为4*(
例如对于4(-1/2)
可能很重要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.