我想從matlab文件中讀取幾條文本行。使用正則表達式函數來提取一些命名的標記。雖然一切工作都很好,但我不能在Matlab中獲得相同的表達式。Matlab正則表達式用命名標記捕獲組
有各種不同的線,我想處理,如:
line1 = 'attr enabled True';
line2 = 'attr width 1.2';
line3 = 'attr size 8Byte';
正則表達式我想出了模樣:
pattern = '^attr +(?<name>\S+) +(?:(?<number>[+-]?\d+(?:\.\d+)?)(?<unit>[a-z,A-z]*)?|(?<bool>(?:[tT][rR][uU][eE]|[fF][aA][lL][sS][eE])))$'
當我運行(在Matlab 2016B) :
[tokens, matches] = regexp(line1, pattern, 'names', 'match');
結果是這樣的:
tokens = 0×0 empty struct array with fields:
name
matches = 0×0 empty cell array
在八度的結果,但是,看起來像:
tokens = scalar structure containing the fields:
name = enabled
number =
unit =
bool = True
matches = { [1,1] = attr enabled True }
我測試了我的正則表達式與regexr.com這表明,倍頻爲正常工作。
當我從正則表達式去除外側拍攝組:
pattern = '^attr +(?<name>\S+) +(?<number>[+-]?\d+(?:\.\d+)?)(?<unit>[a-z,A-z]*)?|(?<bool>(?:[tT][rR][uU][eE]|[fF][aA][lL][sS][eE]))$'
Matlab的輸出:
tokens = struct with fields:
bool: 'True'
name: []
number: []
unit: []
matches = { True }
所以MATLAB開始認識到其他命名令牌的領域,但仍名字字段爲空。此外正則表達式不再是正確的交替... 這是一個關於捕獲組的錯誤還是我對某些東西產生了極大的誤解?
我已經嘗試了第四示例(RE4)和我的結果是我沒有得到非捕獲組的'Apple'標記'(?:(A. +))'。所以即使使用未命名的令牌在Matlab 2016b中也失敗了。這個例子是否真的對你有用(或者說matlab版本之間有區別(迴歸?至少不相關的正則表達式更改應用在matlab 2016b中))? –
我現在已經更新到Matlab 2017a,並且一旦涉及非捕獲組,無論是未命名的令牌還是已命名的令牌都可以工作。(相同的結果,例如(re4)) –
我已經嘗試過re4 2016b和2016a和他們都給出了相同的結果,我會編輯我的答案爲清晰: – Justin