简体   繁体   English

如何使用正则表达式使用 replaceAll 格式化 JavaScript 字符串

[英]How to format a JavaScript string with replaceAll using regex

I am trying to format a kind of a board game notation which consists of tabs and spaces.我正在尝试格式化一种由制表符和空格组成的棋盘游戏符号。 The original string is looking like this:原始字符串如下所示:

1.    \td11-d9    \te7-e10    \n2.    \ta8-c8    \tg7-g10xf10    \n3.    \th11-h9    \tf7-i7    

I used this replace method to clean up all of the tabs and new lines我使用这种替换方法来清理所有选项卡和新行

string.replace(/\s\s+/g, ' ').replaceAll('. ', '.');

So, after that the string is looking like this:所以,在那之后字符串看起来像这样:

1.d11-d9 e7-e10 2.a8-c8 g7-g10xf10 3.h11-h9 f7-i7

However, I want to add more space before the number with the dot.但是,我想在带点的数字之前添加更多空格。 So, the string must look like this with 3 spaces before the number of the move (the number with the dot):因此,字符串必须如下所示,在移动数(带点的数字)之前有 3 个空格:

1.d11-d9 e7-e10   2.a8-c8 g7-g10xf10   3.h11-h9 f7-i7

Can I also make all of these operations with a one line code or just one JavaScript method?我也可以使用一行代码或仅一种 JavaScript 方法进行所有这些操作吗?

You can use lookahead with (?=[1-9]) and (?=[az]) to check if the number add two spaces, and if a letter just add one space.您可以使用带有(?=[1-9])(?=[az])的前瞻来检查数字是否添加两个空格,以及一个字母是否只添加一个空格。

 const string = `1. \td11-d9 \te7-e10 \n2. \ta8-c8 \tg7-g10xf10 \n3. \th11-h9 \tf7-i7` const result = string.replace(/\s+(?=[az])/gi, ' ').replace(/\s+(?=[1-9])/gi, ' ').replaceAll('. ', '.'); console.log(result)

Here is how you can do this in a single .replace call:以下是在单个.replace调用中执行此操作的方法:

 const s = "1. \td11-d9 \te7-e10 \n2. \ta8-c8 \tg7-g10xf10 \n3. \th11-h9 \tf7-i7 "; var r = s.replace(/([.\s])\s*\t|\s+$|\n(?=\d\.)/g, '$1'); console.log(r); //=> "1.d11-d9 e7-e10 2.a8-c8 g7-g10xf10 3.h11-h9 f7-i7"

RegEx Breakup:正则表达式分解:

  • ([.\s])\s*\t : Match dot or a whitespace and capture in group #1 followed by 0+ whitespaces followed by a tab. ([.\s])\s*\t :匹配点或空格并在组 #1 中捕获,然后是 0+ 空格,然后是制表符。 We will put back this replacement using $1我们将使用$1退回此替换
  • | : OR : 或者
  • \s+$ : Match 1+ whitespaces before end \s+$ : 在结束前匹配 1+ 个空格
  • | : OR : 或者
  • \n(?=\d\.) : Match \n if it is followed by a digit and a dot \n(?=\d\.) :匹配\n如果它后跟一个数字和一个点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM