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'
답변 (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
Walter
2018년 2월 28일
Guillaume
2018년 2월 28일
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 [].
Walter Roberson
2018년 2월 28일
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 []
Guillaume
2018년 2월 28일
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.
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!