Regular expression to replace spaces with dashes w

2019-07-07 02:19发布

问题:

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* DEF

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.

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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



回答5:

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.