我有一个变量,它存储一个很大的字符串。这个字符串包含字符、空格、制表符、数字等。我只想在这个字符串的每12位数字之前添加一行新行。
示例:
输入:
# Time interval: from 12/25/2020 02:30 to 12/26/2020 03:30 UTC # abc from 42026, def (pqr) | 34-03N | 074-24E | 2652 m 202012260300 AAXX 26034 42026 32596 50000 11050 21073 37300 49820 83520 333 21065 59010 555 10212= 202012251200 AAXX 25124 42026 32596 60000 10000 21023 37300 49880 84520 333 10034 58020=
202012250300 AAXX 25034 42026 32996 00000 11020 21045 37310 49965 333 21056 58030 555 10212=
输出:
# Time interval: from 12/25/2020 02:30 to 12/26/2020 03:30 UTC # abc from 42026, def (pqr) | 34-03N | 074-24E | 2652 m
202012260300 AAXX 26034 42026 32596 50000 11050 21073 37300 49820 83520 333 21065 59010 555 10212=
202012251200 AAXX 25124 42026 32596 60000 10000 21023 37300 49880 84520 333 10034 58020=
202012250300 AAXX 25034 42026 32996 00000 11020 21045 37310 49965 333 21056 58030 555 10212=
您可以使用以下正则表达式:
(D)(d{12})(D)
匹配一个正好包含12位数字的字符串,并将其替换为插入换行符的匹配字符串:
const str = '# Time interval: from 12/25/2020 02:30 to 12/26/2020 03:30 UTC # abc from 42026, def (pqr) | 34-03N | 074-24E | 2652 m 202012260300 AAXX 26034 42026 32596 50000 11050 21073 37300 49820 83520 333 21065 59010 555 10212= 202012251200 AAXX 25124 42026 32596 60000 10000 21023 37300 49880 84520 333 10034 58020= 202012250300 AAXX 25034 42026 32996 00000 11020 21045 37310 49965 333 21056 58030 555 10212='
console.log(str.replace(/(D)(d{12})(D)/g, '$1n$2$3'))
我会在前瞻(?=bd{12}b)
上进行regex搜索,并用一个换行符替换:
var input = "# Time interval: from 12/25/2020 02:30 to 12/26/2020 03:30 UTC # abc from 42026, def (pqr) | 34-03N | 074-24E | 2652 m 202012260300 AAXX 26034 42026 32596 50000 11050 21073 37300 49820 83520 333 21065 59010 555 10212= 202012251200 AAXX 25124 42026 32596 60000 10000 21023 37300 49880 84520 333 10034 58020=n202012250300 AAXX 25034 42026 32996 00000 11020 21045 37310 49965 333 21056 58030 555 10212=";
var output = input.replace(/(?=bd{12}b)/g, "n");
console.log(input);
console.log(output);