代码之家  ›  专栏  ›  技术社区  ›  gdelab

在Matlab中检查空字符串是否符合regex

  •  0
  • gdelab  · 技术社区  · 6 年前

    regexp 函数是我应该用来查找字符串和正则表达式之间匹配的函数。

    但是,当空字符串符合正则表达式时,它将显示与不符合正则表达式时相同的结果:

    expr1 = 'b'
    regexp('a', expr1, 'match') % Returns empty cell: no match
    regexp('b', expr1, 'match') % Returns cell with 'b'
    regexp('', expr1, 'match')  % Returns empty cell: no match
    
    expr2 = ''
    regexp('a', expr2, 'match') % Returns empty cell: no match
    regexp('', expr2, 'match')  % Returns empty cell: but it matches
    
    expr3 = 'b?'
    regexp('a', expr3, 'match') % Returns empty cell: no match
    regexp('b', expr3, 'match') % Returns cell with 'b'
    regexp('', expr3, 'match')  % Returns empty cell: but it matches
    
    expr4 = '|b'
    regexp('a', expr4, 'match') % Returns empty cell: no match
    regexp('b', expr4, 'match') % Returns cell with 'b'
    regexp('', expr4, 'match')  % Returns empty cell: but it matches
    
    expr5 = '.*'
    regexp('b', expr5, 'match') % Returns cell with 'b'
    regexp('', expr5, 'match')  % Returns empty cell: but it matches
    

    当结果是空单元格时,我无法区分“字符串和正则表达式之间不匹配”和“字符串匹配,但它只是一个空字符串”。

    我如何区分这两种情况?

    另一种方法是使用一个函数来测试一个(可能是空的)字符串(不是它的子字符串)是否与regex完全匹配,但是我在Matlab中找不到它。

    编辑 '' blanks(0) ,但它给出了相同的结果。

    1 回复  |  直到 6 年前
        1
  •  2
  •   gnovice    6 年前

    我不知道为什么您可能需要这样做,但是有一种方法可以让您区分除第四个匹配表达式以外的所有情况下的“no match”和“empty string match”条件 '|b' . 这个表达式似乎试图匹配“没有或没有” 'b' “,我认为这和你以前的表达没有什么不同 'b?' ,这是“ “b” 0次或1次”。

    如果你加上 beginning and end anchors 'emptymatch' option 对于 regexp ,那么你会得到一个空的牢房 {} 对于不匹配项和包含空字符串的单元格 {''} 对于空字符串匹配:

    expr1 = '^b$';
    regexp('a', expr1, 'match', 'emptymatch')   % Result = {}
    regexp('b', expr1, 'match', 'emptymatch')   % Result = {'b'}
    regexp('', expr1, 'match', 'emptymatch')    % Result = {}
    
    expr2 = '^$';
    regexp('a', expr2, 'match', 'emptymatch')   % Result = {}
    regexp('', expr2, 'match', 'emptymatch')    % Result = {''}
    
    expr3 = '^b?$';
    regexp('a', expr3, 'match', 'emptymatch')   % Result = {}
    regexp('b', expr3, 'match', 'emptymatch')   % Result = {'b'}
    regexp('', expr3, 'match', 'emptymatch')    % Result = {''}
    
    expr5 = '^.*$';
    regexp('b', expr5, 'match', 'emptymatch')   % Result = {'b'}
    regexp('', expr5, 'match', 'emptymatch')    % Result = {''}