嗨,我有一個需要匹配的文本字符串,我一直在嘗試 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 將起作用。