英文:
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))", "");
英文:
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.
((?<!\w)-|-(?!\w))
This regex will look for hyphens that have nothing before OR hypen that has nothing behind and replace them.
Using this regex, you can replace those occurrence by nothing, like you did before.
string.replaceAll("((?<!\\w)-|-(?!\\w))", "");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论