本文介绍了正则表达式找到破折号的实例,但不是 <space>dash<space>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很亲近.我正在尝试为 Notepad++ 编写一个正则表达式,用空格替换破折号,忽略 破折号已经带有前/后空格.我意识到我可以用foobarfoo"搜索/替换-"然后搜索-"替换"然后将foobarfoo"转换回-",但是该死的-我正在尝试学习正则表达式!

I am sooo close. I am trying code a regex expression for Notepad++ to replace a dash with a space, ignoring dashes already with a pre/post space. I realize I could search/replace " - " with "foobarfoo" then search for "-" replacing for " " then converting "foobarfoo" back to " - ", but damnit - I'm trying to learn regex!

这是我的问题:

适配器 - BNC 公头到 BNC 母头,直角

适配器 - BNC 公头到 BNC 母头,直角

(注意BNC 女性"中消失的破折号)

(note the disappearing dash in "BNC Female")

我最接近的是使用这个:/(?:[^( )])\-(?:[^( )])/g

The closest I am getting is using this:/(?:[^( )])\-(?:[^( )])/g

但这会导致它找到前面的单个字母、破折号和后面的单个字母:

but that results with it finding the single letter ahead, the dash, and the single letter following:

适配器 - BNC 公头到 BNC-F母头,直角

为什么要选择前/后字符?这不是:

WHY is it selecting the pre/post characters? Is this not:

(?:[^( )]) 查找除空格以外的任何内容(作为非捕获组)...

(?:[^( )]) find anything except a space (as a noncapturing group)...

\- ... 后跟破折号 ...

\- ... that follows with a dash ...

(?:[^( )]) ... 后跟除空格外的任何内容(作为非捕获组)

(?:[^( )]) ... and is followed by anything except a space(as a noncapturing group)

我更接近的是我将第一项替换为 (?=[^( )]) 但如果我将第三项更改为 (?![^( )]) 我回到了我开始的地方 - 只需选择两个空格之间的破折号.GRRRR.

I get even closer is I replace the first term with (?=[^( )]) but if I change the third term to (?![^( )]) I'm back to where I started - just selecting the dash in between the two spaces. GRRRR.

更多示例请访问 http://regexr.com/444i2

推荐答案

要忽略已经带有前/后空间的破折号,您可以使用肯定的 lookarounds 断言左侧和右侧的内容是非空白字符 \S

To ignore dashes already with a pre/post space you could use positive lookarounds to assert that what is on the left and on the right are a non whitespace character \S

在替换中使用空格.

(?<=\S)-(?=\S)

正则表达式演示

这篇关于正则表达式找到破折号的实例,但不是 &lt;space&gt;dash&lt;space&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 19:15