Lookaround 正则表达式来评估双方?

发布于 2024-11-19 03:44:32 字数 638 浏览 6 评论 0原文

好吧,我有一个非常棘手的正则表达式问题。

我需要将以下字符串中的 + 号匹配并替换为空格,因此左侧的字符串必须成为右侧的字符串。

1: word+word   =  word word
2: word+++word =  word + word
3: word.+word  =  word. word
4: word,+word  =  word, word

我已经成功地用这个来确定大部分的内容,它检查加号之前和之后的字符串:

(?<=[\w\.,])\+(?=[\w])

但是,我一次只能在 (2) 中确定一组相邻的加号:

(?<=[\w\.,\+])\+(?=[\w]) // gets the left plus sign
2: word+++word =  word++ word

(?<=[\w\.,])\+(?=[\w\+]) // gets the right plus sign
2: word+++word =  word ++word

在我当前的正则表达式中 ,疲惫不堪的状态下,我想知道是否需要将模式包装在更大的条件中,或者是否需要在环视中实现“任一”或“模式”。有正则表达式专家愿意尝试一下吗?

Ok, I have a pretty tricky regex problem.

I need to match and replace the + signs in the following strings with whitespace, thus the strings on the left must become the strings on the right.

1: word+word   =  word word
2: word+++word =  word + word
3: word.+word  =  word. word
4: word,+word  =  word, word

I've managed to nail most of 'em with this, which checks for strings before and after plus signs:

(?<=[\w\.,])\+(?=[\w])

However, I can only nail one set of the adjacent plus signs in (2) at a time:

(?<=[\w\.,\+])\+(?=[\w]) // gets the left plus sign
2: word+++word =  word++ word

(?<=[\w\.,])\+(?=[\w\+]) // gets the right plus sign
2: word+++word =  word ++word

In my current regex be-frazzled state, I'm wondering if I need to wrap the pattern in a larger condition, or if I need to implement an either or pattern in the lookarounds. Any regex mavens out there care to give this a whirl?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

じее 2024-11-26 03:44:32

这应该适用于您的示例:

(?<!\+)\+|\+(?!\+)

将其替换为空格。

示例:

perl -E "$_='a+b++a+++b++++c+++++d'; s/(?<!\+)\+|\+(?!\+)/ /g; say"

输出:

a b  a + b ++ c +++ d

This should work on your examples:

(?<!\+)\+|\+(?!\+)

Replace that with spaces.

Example:

perl -E "$_='a+b++a+++b++++c+++++d'; s/(?<!\+)\+|\+(?!\+)/ /g; say"

Outputs:

a b  a + b ++ c +++ d
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文