您可以使用sprintf
和regexprep
的組合。
my_format = @(x)regexprep(sprintf('%.E',x),'E\+0*','E');
例子:
>> my_format(1E4)
ans =
1E4
>> my_format(2E12)
ans =
2E12
這並不適合於所有情況:
>> my_format(5) % Expect 5E0
ans =
5E
>> my_format(1E-4) % Expect 1E-4
ans =
1E-04
我們可以修復與token第一種情況:
f2 = @(x)regexprep(sprintf('%.E',x),'E\+0*(\d)','E$1');
>> {f2(1E4), f2(1E20), f2(5)}
ans =
'1E4' '1E20' '5E0'
我們可以用令牌和a來修復第二種情況?
quantifier:
>> f3 = @(x)regexprep(sprintf('%.E',x),'E\+?(-?)0*(\d)','E$1$2');
>> {f3(1E4), f3(1E20), f3(5),f3(1E-1),f3(2E-12)}
ans =
'1E4' '1E20' '5E0' '1E-1' '2E-12'
爲了解釋,sprintf('%.E',x)
格式x
科學記數法同E
,例如1E+04
,然後找到
'E\+?(-?)0*(\d)'
E The literal E
\+?(-?) Either a + or a -; if - then save to group $1
0* As many 0s as it can match, subject to...
(\d) At least one digit, saves digit to group $2
最後,匹配的文本替換爲E$1$2
,那是字面E
,然後組$1
(負發現E-
如果發現E+
標誌如果沒有)和組$2
(一單個數字)。