开发者

Regular expression to replace spaces with dashes within a sub string.

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.

Source:

ABC *This is a sub string* DEF

My attempt at a regular expression:

/\s/g

If I use the regular expression to match spaces and replace I get the following result:

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

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

Here is what I'm trying to achieve:

ABC *This-is-a-sub-string* 开发者_如何学JAVADEF

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.

Any help will be appreciated.


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.

The regex

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

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


s/(?<!\*)\s(?!\*)(?!$)/-/g

If TextMate supports Perl style regex commands (I have no experience with it all, sorry), this is a one-liner that should work.


try this one

/(?<=\*.*)\s(?=.*\*)/g

but it won't work in javascript if you want to use it in it, since it uses also lookbehind which is not supported in js


Try this: \s(\*[^*]*\*)\s. It will match *This is a sub string* in group 1. Then replace to -$1-.


Use this regexp to get spaces from within asterisks (.)(*(.(\ ).)*)(.) Take 4th element of the array provided by regex {4} and replace it with dashes.

I find this site very good for creating regular expressions.


It depends on your programming language but in many of them you can use lambda functions with your regular expression replacement statements and thereby perform further replacement on substrings.

Here's an example in Python:

string = "ABC *This is a sub string* DEF"
import re
new_string = re.sub("\*(.*?)\*", lambda x: '*' + x.group(1).replace(" ", "-") + '*', a)

That should give you ABC *This-is-a-sub-string* DEF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜