从字符串中移除破折号,但在被(a-z)包围时不移除破折号。

huangapple go评论70阅读模式
英文:

Remove dash from string but not from middle when its surrounded by (a-z)

问题

我阅读了类似的问题,但那些问题并没有完全回答我的问题。

我想从字符串中删除任何破折号,但不包括字符串中被(a-z)或(A-Z)包围的破折号,就像我的示例测试案例一样。

我已经使用了这个正则表达式代码,但它会清除所有的破折号:

string.replaceAll("\\-", "");

测试案例

  • --good
  • -good
  • g-ood*
  • g--ood
  • good-
  • good--

结果

  • good
  • good
  • g-ood*
  • good
  • good
  • good
英文:

I read similar questions but those are not answer exactly to my question.

i want to remove any dash from my string but not that dash in middle of string that surrounded by (a-z) or (A-Z) like my example test case.

i already use this regex code but it clean all dash:

string.replaceAll("\\-", "");

Test Case

  • --good
  • -good
  • g-ood*
  • g--ood
  • good-
  • good--

Result

  • good
  • good
  • g-ood*
  • good
  • good
  • good

答案1

得分: 2

使用正则表达式来进行这样的操作是正确的做法。然而,您的正则表达式捕获了每个连字符。您需要检查连字符前后是否有字母。

((?<!\w)-|-(?!\w))

这个正则表达式将查找在连字符前面没有字母或者在连字符后面没有字母的连字符,并将其替换掉。

使用这个正则表达式,您可以像之前那样将这些情况替换为空字符串。

string.replaceAll("((?<!\\w)-|-(?!\\w))", "");

这里有一个供您测试更多案例的regex101链接

英文:

Using a regex to do that is the right thing to do. However, your regex is capturing every hyphens. What you need is to check for letter before and after.

((?&lt;!\w)-|-(?!\w))

This regex will look for hyphens that have nothing before OR hypen that has nothing behind and replace them.

从字符串中移除破折号,但在被(a-z)包围时不移除破折号。

Using this regex, you can replace those occurrence by nothing, like you did before.

string.replaceAll(&quot;((?&lt;!\\w)-|-(?!\\w))&quot;, &quot;&quot;);

here is a regex101 for you to test more cases

huangapple
  • 本文由 发表于 2020年4月9日 04:41:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61109658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定