英文:
How to insert a bracket between the specified alphabet (i.e. A, D, F, R) and the digit using regular expression?
问题
如何使用正则表达式在指定的字母(即A、D、F、R)和数字之间插入括号?
输入:
A1
F42
D3
R6
预期输出:
(A)1
(F)42
(D)3
(R)6
我尝试过的方法:
let inputString = "f42";
let expPattern = /[ADFR]\d{1,3}/ig;
console.log(inputString.replace(expPattern, "($&)"));
它只返回"$0"。
我如何实现替换?
英文:
How to insert a bracket between the specified alphabet (i.e. A, D, F, R) and the digit using regular expression?
input:
A1
F42
D3
R6
Expected output:
(A)1
(F)42
(D)3
(R)6
What I have tried:
let inputString="f42"
let expPattern=/[ADFR]\d{1,3}/ig;
console.log(inputString.replace(expPattern,"(`$0`)"));
It returns "$0" only.
How can I implement the replacement?
答案1
得分: 3
你应该将字母和数字分别放入不同的捕获组中,这样你可以在替换字符串中引用它们:
let inputString = "F42";
let expPattern = /([ADFR])(\d{1,3})/ig;
console.log(inputString.replace(expPattern, "($1)$2"));
英文:
You should enclose the alphabet and the digits in separate capture groups so you can reference them in the replacement string:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let inputString="F42"
let expPattern=/([ADFR])(\d{1,3})/ig;
console.log(inputString.replace(expPattern,"($1)$2"));
<!-- end snippet -->
答案2
得分: 2
Sure, here are the translated parts:
如果您想在替换中使用完全匹配,可以使用正向预查 (?=\d{1,3}\b)
来断言右侧有 1-3 位数字。
为了防止部分匹配,您可以使用单词边界 \b
。
在替换中使用完全匹配,表示为 $&
。
请参见正则表达式演示中的所有替换。
let inputString = "F42";
let expPattern = /\b[ADFR](?=\d{1,3}\b)/ig;
console.log(inputString.replace(expPattern, "($&)"));
(Note: I've retained the code as requested and only translated the non-code parts.)
英文:
If you want to use the full match in the replacement, you can make use of a positive lookahead (?=\d{1,3}\b)
asserting 1-3 digits to the right.
To prevent partial matches, you can use word boundaries \b
In the replacement use the full match denoted as $&
See a regex demo with all the replacements.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let inputString="F42"
let expPattern=/\b[ADFR](?=\d{1,3}\b)/ig;
console.log(inputString.replace(expPattern,"($&)"));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论