嗨,我有一个需要匹配的文本字符串,我一直在尝试 pat match() 但没有掌握它。文本是文件名。 我需要识别具有特定模式的所有文件:
“AB0007 25092019 0822.txt”:
2个大写字母。 “AB”实际上总是。
4位数字和一个空格
ddMMYYYY(或仅 8 位数字)和一个空格
4位数
“。TXT”
我一直在尝试但失败了很多版本,最新的:
file="AB0007 25092019 0822.txt" // 用于测试;最终它将成为我循环浏览的文件列表中的一个项目
pattern="AB"+"\d{4}"+"\s"+"\d{8}"+"\s"+"\d{4}";
拍拍匹配(文件,模式);
任何帮助,将不胜感激!
JSL有一个正则表达式进行传统正则表达式匹配的函数和匹配如果需要,可以使用正则表达式片段的函数。 最后一个例子暗示了为什么你可能想要使用匹配功能。还要注意 ^...$ 或 PatPos(0)...PatRPos(0) 逻辑的额外位,以确保整个文件名匹配。
file = "AB0007 25092019 0822.txt"; // for testing; eventually it will be an item in a file list that I cycle through
// decide if using (1) pure regex,
Show( Regex( file, "^AB\d{4}\s\d{8}\s\d{4}\.txt$" ) ); // "AB0007 25092019 0822.txt", or missing (.) if not matched
// or (2) pure pattern matching,
digit = Pat Any( "0123456789" );
pattern = Pat Pos( 0 ) + "AB" + Pat Repeat( digit, 4, 4 ) + " " + Pat Repeat( digit, 8, 8 ) + " " + Pat Repeat( digit, 4, 4 ) + ".txt" + Pat R Pos( 0 );
Show( Pat Match( file, pattern ) ); // rc is 1, it matches, 0 if fails to match
// or (3a) mix of both
pattern = Pat Pos( 0 ) + "AB" + Pat Regex( "\d{4}" ) + Pat Regex( "\s" ) + Pat Regex( "\d{8}" ) + Pat Regex( "\s" ) + Pat Regex( "\d{4}" ) + ".txt" + Pat R Pos( 0 );
Show( Pat Match( file, pattern ) ); // rc is 1, it matches, 0 if fails to match
// or collapse the mix (3b) a bit
pattern = Pat Pos( 0 ) + "AB" + Pat Regex( "\d{4}\s\d{8}\s\d{4}" ) + ".txt" + Pat R Pos( 0 );
Show( Pat Match( file, pattern ) ); // rc is 1, it matches, 0 if fails to match
// why you might choose (2) or (3a) -- you can capture substrings like the date part using the >> operator:
digit = Pat Any( "0123456789" );
pattern = Pat Pos( 0 ) + "AB" + Pat Repeat( digit, 4, 4 ) + " " + Pat Repeat( digit, 8, 8 ) >> datepart + " " + Pat Repeat( digit, 4, 4 ) + ".txt" + Pat R Pos( 0 );
Show( Pat Match( file, pattern ),informat(datepart,"ddmmyyyy") ); // rc is 1, Informat(datepart, "ddmmyyyy") = 25Sep2019;正则表达式(文件,“^AB\d{4}\s\d{8}\s\d{4}\.txt$”)=“AB0007 25092019 0822.txt”;
帕特匹配(文件,模式)= 1;
帕特匹配(文件,模式)= 1;
帕特匹配(文件,模式)= 1;
帕特匹配(文件,模式)= 1;
Informat(日期部分,“ddmmyyyy”)= 25Sep2019;
JMP 的正则表达式建立在模式匹配函数之上;一个都不会比另一个快。 这正则表达式函数将正则表达式转换为等效的模式匹配函数,因此 PatMatch 将起作用。