regexptranslate
将文本转换为正则表达式
说明
示例
使用 regexptranslate 函数转换字符向量中的特殊字符。然后将结果用作 regexp 中的正则表达式。
创建包含字符 '\n' 的字符向量。
chr = 'The sequence \n generates a new line.'chr = 'The sequence \n generates a new line.'
创建一个正则表达式,以查找作为两个连续字符 '\' 和 'n' 的 '\n' 序列。由于 regexp 函数将 '\n' 解释为换行符,因此可使用 regexptranslate 创建一个正则表达式以转义 '\n'。
pattern = regexptranslate('escape','\n')
pattern = '\\n'
求出 '\n' 在 chr 中的起始索引。要防止 regexp 将 '\n' 解释为换行符,请使用 pattern 作为正则表达式。
idx = regexp(chr,pattern)
idx = 14
在不转义 '\n' 的情况下调用 regexp。由于 regexp 将 '\n' 解释为换行符,因此它不查找 chr 中的字面字符。regexp 函数在找不到匹配项时返回空数组。
idx = regexp(chr,'\n')idx =
[]
创建一个字符串。
str = "Put your money in."str = "Put your money in."
将文本 '$0.02' 指定为要替换单词 'money' 的文本。要对 '$' 和 '.' 字符进行转义,请使用 regexptranslate。
r = regexptranslate('escape','$0.02')
r = '\$0\.02'
使用 regexprep 函数替换 'money'。
newStr = regexprep(str,'money',r)newStr = "Put your $0.02 in."
创建一个包含文件名的字符串数组。然后,只找出以 '.mat' 结尾的文件名。
str = ["test1.mat","myfile.mat","my-matlab-script.m", ... "jan30.mat","table3.xls"]
str = 1×5 string
"test1.mat" "myfile.mat" "my-matlab-script.m" "jan30.mat" "table3.xls"
要匹配包含正则表达式的字符串,请指定 '*.mat' 作为正则表达式。然后使用 regexptranslate 函数转换通配符 '*'。
pattern = regexptranslate('wildcard','*.mat')
pattern = '.*\.mat'
使用 pattern 指定的正则表达式查找 str 中匹配的元素。
matches = regexp(str,pattern)
matches=1×5 cell array
{[1]} {[1]} {0×0 double} {[1]} {0×0 double}
创建逻辑数组 TF,它包含 1,其中 str 对应的元素与 pattern 匹配。然后,使用 TF 对 str 进行索引,以显示以 '.mat' 结尾的文件名。
tf = ~cellfun('isempty',matches);
newStr = str(tf)newStr = 1×3 string
"test1.mat" "myfile.mat" "jan30.mat"
创建包含单词的字符向量,这些单词由空白字符(例如空格和换行符)分隔。
chr = 'Whose woods these are I think I know.'; chr = [chr newline 'His house is in the village though']
chr =
'Whose woods these are I think I know.
His house is in the village though'
指定 '\s' 作为与空白字符匹配的正则表达式。然后替换 chr 中的这些字符。
expression = '\s'; newChr = regexptranslate('flexible',chr,expression)
newChr = 'Whose\swoods\sthese\sare\sI\sthink\sI\sknow.\sHis\shouse\sis\sin\sthe\svillage\sthough'
输入参数
转换的类型,指定为字符向量或字符串标量。您可以使用表中的选项转换特殊字符或通配符,或者将文本替换为匹配的正则表达式。
转换的类型 | 描述 |
|---|---|
| 转换 |
| 转换 |
| 将 此语法等效于 |
输入文本,指定为字符向量、字符向量元胞数组或字符串数组。
版本历史记录
在 R2006a 之前推出
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)