我在linux和windows上使用MatLab时遇到了regexp()的不同行为.

Linux

test_string = '<some_path>/tool/test/unit_test'
seperator = sprintf('%stest%s',filesep,filesep)
regexp(test_string, seperator,'split')

输出:

1×2 cell array
{'<some_path>/tool'}    {'unit_test'}

Windows

test_string = '<some_path>\tool\test\unit_test'
seperator = sprintf('%stest%s',filesep,filesep)
regexp(test_string, seperator,'split')

输出

1×1 cell array
{'<some_path>\src\tool\test\unit_test'}

这个代码片段在Linux上的输出代表了我想要的行为.是否有人可以解释或指向资源以了解发生了什么?

推荐答案

Linux(/)和Windows(\)中的路径分隔符不同.

\字符是一个特殊的正则表达式元字符,用于形成"正则表达式转义",如\d以匹配数字等.要匹配文字反斜杠,必须将其加倍,或escaped.

要转义任何特殊的正则表达式元字符,可以使用regexptranslate(op, str)并将op设置为escape:

seperator = sprintf('%stest%s',regexptranslate('escape',filesep), regexptranslate('escape',filesep))

其他op个可能值包括:

Type of Translation Description
'escape' Translate all special characters in str, such as '$', '.', '?','[', so that they are treated as literal characters when used in regexp, regexpi, and regexprep. The translation inserts a backslash, or escape, character, '\', before each special character in str.
'wildcard' Translate all wildcard and '.' characters in str so that they are treated as literal wildcard characters and periods when used in regexp, regexpi, and regexprep. The translation replaces all instances of '*' with '.*', all instances of '?' with '.', and all instances of '.' with '\.'.
'flexible' Replace text in str with a regular expression that matches the text. If you specify 'flexible', then also specify a regular expression to use as a replacement: newStr = regexptranslate('flexible',str,expression). The expression input can be a character vector or string scalar.

This syntax is equivalent to newStr = regexprep(str,expression,regexptranslate('escape',expression)).

Linux相关问答推荐

当页面对齐关闭时,x86—64上的对象中的成员初始化器的Clang代码生成错误?

BASH-SCRIPT-在特定行合并两个文件

Shell 脚本程序 - 从日志(log)文件中过滤磁盘空间利用率超过 80% 的行

使用来自 yocto build 而不是主机系统的 protoc

从另一个文件中的大文件中查找行的最快方法

为什么rsp寄存器从0x7FFFFFFFDFD0开始

为什么`__vfprintf_internal`(`stdio.h`中的`printfn`)强制`$rbp`在我的x86-64机器上向前跳转6313864字节?

我需要制作一个 awk 脚本来解析文件中的文本.我不确定我是否做得正确

如何在初始化脚本中以特定用户身份运行命令?

Linux/Unix 手册页语法约定

Linux 进程在后台 - 在作业(job)中 Stopped停止?

使用 AWS cli 从 AWS 机密管理器解析机密

如何在 linux 'screen' 中搜索任何单词

如何更改目录中所有文件中所有出现的单词

如何仅使用 SED 获得第二行

Linux 非阻塞 fifo(按需日志(log)记录)

如何将输出从 grep 传送到 cp?

Linux:在目录下的文件列表中搜索特定单词

sed - 如何使用 sed 进行正则表达式组

如何查看线程在哪个 CPU 内核中运行?