简体   繁体   English

REGEX:在Octave上使用命名组替换字符串

[英]REGEX: string replacement using named groups on Octave

I'm aware of the Pythonic way to replace a pattern in a String using named groups: 我知道使用命名组替换String的模式的Pythonic方法:

r"(?P<p>(\.+))".sub(r' \g<p> ', 'test sentence..')

Is it possible to do it on Octave (I'm using v3.8.0)? 是否可以在Octave上执行此操作(我正在使用v3.8.0)? I tried some variations, as below, but no success. 我尝试了一些变体,如下所示,但没有成功。

regexprep('test sentence..', '(?<p>(\.+))', ' \k<p> ')
regexprep('test sentence..', '(?<p>(\.+))', ' $<p> ')

As you may have notice, this simple example focus on capturing the String '..' and adding a space before and after it. 您可能已经注意到,这个简单的示例着重于捕获String '..'并在其前后添加一个空格。

Input: 'test sentence..'
Expected Output: 'test sentence .. '
Group Match: p = '..'

I'm able to capture the match normally using $1 , $2 , etc but not as named token. 我通常可以使用$1$2等捕获匹配,但是不能作为命名令牌。

With @horchler help, we have narrowed down the problem and it seems only Octave present the described problem. 在@horchler帮助下,我们缩小了范围,似乎只有Octave提出了所描述的问题。 From Octave documentation, we have: 从Octave文档中,我们可以:

Built-in Function: outstr = regexprep (string, pat, repstr) Built-in Function: outstr = regexprep (string, pat, repstr, "opt1", ...) Replace occurrences of pattern pat in string with repstr. 内置函数:outstr = regexprep(字符串,pat,repstr)内置函数:outstr = regexprep(字符串,pat,repstr,“ opt1”,...)用repstr替换字符串中出现模式pat的情况。

The pattern is a regular expression as documented for regexp. 该模式是正则表达式,记录在regexp中。 See regexp. 请参阅regexp。

The replacement string may contain $i, which substitutes for the ith set of parentheses in the match string. 替换字符串可能包含$ i,它替换匹配字符串中的第i个括号。 For example, 例如,

  regexprep ("Bill Dunn", '(\\w+) (\\w+)', '$2, $1') returns "Dunn, Bill" 

Options in addition to those of regexp are 除了regexp以外的选项还有

'once' Replace only the first occurrence of pat in the result. “一次”仅替换结果中第一次出现的拍拍。 'warnings' This option is present for compatibility but is ignored. '警告'提供此选项是为了兼容性,但将被​​忽略。

So, they do not mention any support to Named Tokens as MATLAB documentation does. 因此,他们没有像MATLAB文档那样提到对Named Tokens任何支持。 This makes me believe the current version of Octave does not support them along with regexprep function. 这使我相信当前的Octave版本不支持regexprep函数。 As far as I know, a major concern of Octave developers is to make sure all MATLAB functionality is there at all, but it seems that one is still not supported. 据我所知,Octave开发人员的主要关注点是确保所有MATLAB功能都已存在,但似乎仍然不支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM