regex Safari的JS正则表达式lookbehind/lookahead的替代项

ecbunoof  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(137)

我在JS中有一个正则表达式
/(?〈!\r)\n/gm)中的一个或多个消息。
下面是我的“留言”。

'Hello, please can you send £100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you'

正如您在上面看到的,我在链接内接收\r\n值,这是新行字符,因此它无法识别链接并以多行显示。
但是上面的正则表达式在chrome中正确地将其转换为链接,但由于lookbehind/lookahead,在safari中不起作用。
花了一些时间试图想一个好的变通办法,但没有找到。有什么见解吗?
谢谢你!

e5njpo68

e5njpo681#

您可以使用match而不是split,然后在多行文字以\r\n?分隔时进行比对。
下面是一个代码片段,其中包含原始方法和建议的方法:

const message = 'Hello, please can you send £100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you';
// With look-behind
const messageArray = message.split(/(?<!\r)\n/gm);
console.log(messageArray);
// Without lookbehind
const messageArray2 = message.match(/^.*$(\r\n?.*$)*/gm);
console.log(messageArray2);

输出相同。

a11xaf1n

a11xaf1n2#

假设\r\n仅位于链接内,而\n位于链接外,您可以先通过删除\r\n来恢复链接,然后按\n进行拆分:

const input = 'Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  \n\nhttps://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/ \r\nwhat-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 \n\nThank you';
let result = input.replace(/ *\r\n/g, '').split(/\n/);
console.log(result);

输出量:

[
  "Hello, please can you send &#163;100.00 to  MNBVCXZLSTERIA1 on  04/08/21  ",
  "",
  "https://www.co-operativebank.co.uk/help-and-support/faqs/accounts/savings/isas/what-happens-if-i-put-too-much-money-in-my-cash-isa/PROD-2740 ",
  "",
  "Thank you"
]

注意:要删除空数组项,您可以改为使用以下命令:.split(/\n+/)

相关问题