Regex Replace cannot lock on to correct character offset in replacement

Can someone help me figure out the following:
if true
myStr = 'margins1.1.5 Configuration management1.1.6 Cool engineering1.1.7 Modeling';
expression = '[^\d^ ]\d(\.\d){1,}';
replace_0 = ' [$0]';
replace_1 = ' [$1]';
newStr_0 = regexprep(myStr,expression,replace_0)
newStr_1 = regexprep(myStr,expression,replace_1)
desiredStr = 'margins [1.1.5] Configuration management [1.1.6] Cool engineering [1.1.7] Modeling'
end
I am getting the following and want to get desiredStr
newStr_0 =
'margin [s1.1.5] Configuration managemen [t1.1.6] Cool engineerin [g1.1.7] Modeling'
newStr_1 =
'margin [.1.5] Configuration managemen [.1.6] Cool engineerin [.1.7] Modeling'
desiredStr =
'margins [1.1.5] Configuration management [1.1.6] Cool engineering [1.1.7] Modeling'

Risposte (1)

I don't understand why you have two consecutive replacements.
This will give you the correct result:
regexprep(myStr, '(\d\.)+\d', ' [$0]')
Your regex doesn't make much sense, [^\d^ ] means match any character that do not match \ or d or ^ or a space. Note that escapes don't work in [] and the ^ has only special meaning as the first character inside []. edit: brain went mushy. See below for correct interpretation.
edit: Note that the above will only match numbers from 1 to 9, so not 1.1.10. if the latter is desired then use \d+ instead of \d.

5 Commenti

That won't work for the case: 'dated September 25, 2000.3.2 Exhibit 2,'
it will give you: 'dated September 25, 200 [0.3.2] Exhibit 2,'
hence the extra trickery.
As per my edit, if you want it to match multiple digit numbers replace \d by \d+.
If you want to avoid adding an extra space when one already exists:
regexprep(myStr, ' ?((\d+\.)+\d+)', ' [$1]')
"Note that escapes don't work in [] "
According to what? This escaped character works:
>> regexp('abcd2345','[^\d]+','match')
ans =
'abcd'
The regular expression help also includes this example: " \S Any non-white-space character; equivalent to [^\f\n\r\t\v]". It is not clear how these show that escaped characters do not work inside [].
Yup and you can need to escape ] characters inside a []. There is a special convention about ] immediately after [ or immediately after [^ but those conventions are not enough to remove the need to escape ] characters inside []. What is true is that quantifiers and dot and () lose special meaning inside []
Yes, not sure what I was on about. Of course, escapes work in []. Still, the second ^ in the [] is a literal ^ not a do not match next character indicator. So the [^\d^ ] means do not match any of digit, ^ or space.

Accedi per commentare.

Categorie

Prodotti

Richiesto:

il 28 Feb 2018

Modificato:

il 28 Feb 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by