在子字符串中用破折号替换空格的正则表达式. [英] Regular expression to replace spaces with dashes within a sub string.

查看:55
本文介绍了在子字符串中用破折号替换空格的正则表达式.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力寻找一种方法来用字符串中的破折号替换空格,但只能替换字符串特定部分内的空格.

I've been struggling to find a way to replace spaces with dashes in a string but only spaces that are within a particular part of the string.

来源:

ABC *This is a sub string* DEF

我对正则表达式的尝试:

/\s/g

如果我使用正则表达式来匹配空格并替换,我会得到以下结果:

ABC-*This-is-a-sub-string*-DEF

但我只想替换由两个星号包围的文本中的空格.

But I only want to replace spaces within the text surrounded by the two asterisks.

这是我想要实现的目标:

ABC *This-is-a-sub-string* DEF

不确定为什么我使用的正则表达式类型,因为我在 TextMate 中使用查找和替换并启用了正则表达式选项.

Not sure why type of regular expressions I'm using as I'm using the find and replace in TextMate with Regular Expressions option enabled.

请务必注意,我将运行此正则表达式搜索和替换的字符串将具有不同的文本,但我想要匹配的只是星号内的空格.

It's important to note that the strings that I will be running this regular expression search and replace on will have different text but it's just the spaces within the asterisks that I want to match.

任何帮助将不胜感激.

推荐答案

要识别被星号包围的空格,关键的观察是,如果星号只成对出现,则您要查找的空格后面总是跟有一个奇数个星号.

To identify spaces that are surrounded by asterisks, the key observation is, that, if asterisks appear only in pairs, the spaces you look for are always followed by an odd number of asterisks.

正则表达式

\ (?=[^*]*\*([^*]*\*[^*]*\*)*[^*]*$)

将匹配应该被替换的一次.Textmate 必须支持前瞻断言才能使其工作.

will match the once that should be replaced. Textmate would have to support look-ahead assertions for this to work.

这篇关于在子字符串中用破折号替换空格的正则表达式.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆