【问题标题】:regexp parsing in matlabmatlab中的正则表达式解析
【发布时间】:2012-08-20 11:13:19
【问题描述】:

我有一个像这样的 3x1 元胞数组:

name1 = text1
name2 = text2
name3 = text3

我想将其解析为 1x2 的单独单元格,例如 name1 、 text1 。将来我想将 text1 视为字符串以与其他字符串进行比较。我该怎么做?我正在尝试使用正则表达式和令牌,但我无法为此编写适当的公式,如果有人可以帮助我,我将不胜感激!

【问题讨论】:

  • (\w+)\s=\s(\w+)

标签: regex parsing matlab


【解决方案1】:

这段代码

input = {'name1 = text1';
         'name2 = text2';
         'name3 = text3'};

result = cell(size(input, 1), 2);
for row = 1 : size(input, 1)
    tokens = regexp(input{row}, '(.*)=(.*)', 'tokens');
    if ~isempty(tokens)
        result(row, :) = tokens{1};
    end
end

产生结果

result = 
    'name1 '    ' text1'
    'name2 '    ' text2'
    'name3 '    ' text3'

请注意,等号周围的空格会被保留。您可以通过调整正则表达式来修改此行为,例如也可以试试'([^\s]+) *= *([^\s]+)'

result = 
    'name1'    'text1'
    'name2'    'text2'
    'name3'    'text3'

编辑:基于user1578163的cmets。

Matlab 还支持不那么贪婪的量词。例如,如果文本包含空格,则正则表达式 '(.*?) *= *(.*)'(注意星号后的问号)有效。会变身

input = {'my name1 = any text1';
         'your name2 = more text2';
         'her name3 = another text3'};

进入

result = 
    'my name1'      'any text1'    
    'your name2'    'more text2'   
    'her name3'     'another text3'

【讨论】:

  • 有什么方法可以在您的第一种方法中删除空格?第二个不是很好,但第一个是理想的,只需要删除空格即可比较字符串。顺便问一下,你建议我如何学习正则表达式和标记?以这种方式对 matlab 的帮助还不够,示例太少,无法理解如何组合所有“符号”。
  • 我知道这个表达式可以处理单个字符串,但是如何进入这些字符串的单元格呢? regexprep(s,'[^\w'']','')
  • @user1578163:尝试使用tokens{1}{1}tokens{1}{2} 直接获取令牌。为什么第二个正则表达式没有按预期工作?哪些字符串失败了?
  • @user1578163:我从 SED 教程 grymoire.com/Unix/Sed.html 学习了正则表达式。
猜你喜欢
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 2011-03-20
  • 2012-07-08
  • 2010-10-23
  • 2017-07-10
相关资源
最近更新 更多