如何使用正则表达式在指定的字母(即A、D、F、R)和数字之间插入括号?

huangapple go评论90阅读模式
英文:

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)和数字之间插入括号?

输入:

  1. A1
  2. F42
  3. D3
  4. R6

预期输出:

  1. (A)1
  2. (F)42
  3. (D)3
  4. (R)6

我尝试过的方法:

  1. let inputString = "f42";
  2. let expPattern = /[ADFR]\d{1,3}/ig;
  3. 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:

  1. A1
  2. F42
  3. D3
  4. R6

Expected output:

  1. (A)1
  2. (F)42
  3. (D)3
  4. (R)6

What I have tried:

  1. let inputString="f42"
  2. let expPattern=/[ADFR]\d{1,3}/ig;
  3. console.log(inputString.replace(expPattern,"(`$0`)"));

It returns "$0" only.

How can I implement the replacement?

答案1

得分: 3

你应该将字母和数字分别放入不同的捕获组中,这样你可以在替换字符串中引用它们:

  1. let inputString = "F42";
  2. let expPattern = /([ADFR])(\d{1,3})/ig;
  3. 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 -->

  1. let inputString=&quot;F42&quot;
  2. let expPattern=/([ADFR])(\d{1,3})/ig;
  3. console.log(inputString.replace(expPattern,&quot;($1)$2&quot;));

<!-- end snippet -->

答案2

得分: 2

Sure, here are the translated parts:

如果您想在替换中使用完全匹配,可以使用正向预查 (?=\d{1,3}\b) 来断言右侧有 1-3 位数字。

为了防止部分匹配,您可以使用单词边界 \b

在替换中使用完全匹配,表示为 $&amp;

请参见正则表达式演示中的所有替换。

  1. let inputString = "F42";
  2. let expPattern = /\b[ADFR](?=\d{1,3}\b)/ig;
  3. console.log(inputString.replace(expPattern, "($&amp;)"));

(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 $&amp;

See a regex demo with all the replacements.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. let inputString=&quot;F42&quot;
  2. let expPattern=/\b[ADFR](?=\d{1,3}\b)/ig;
  3. console.log(inputString.replace(expPattern,&quot;($&amp;)&quot;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月5日 13:52:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定