V 2022 Q2版
數(shù)據(jù)處理過程中智玻,時常會遇到從字符串中提取特定內(nèi)容的場景,如從FTP的連接串中卫病,抽取用戶名乌妒。
ftp連接串:ftp://anonymous:guest@ftp.ncbi.nlm.nih.gov:125/gdgdsg/wrwq
在C語言中可以用scanf函數(shù),在DatistEQ如何實現(xiàn)呢撤蚊?
DatistEQ中,提供MatchGroup和MatchGroups兩個函數(shù),使用正則表達式席镀,抽取一個或一組數(shù)據(jù)。
MatchGroup函數(shù)格式:
string MatchGroup(string,regexString,[Optional] groupNames,[Optional] regexOptions)
說明:
分組正則表達式匹配顶捷,返回第一個匹配結(jié)果屎篱。
string,源文本字符串重虑;
regexString秦士,正則表達式;
groupNames提针,可選項曹傀,默認為空,多個組名以|分隔;
RegexOptions嗜价,可選項,默認為Compiled|IgnoreCase炭剪,用于設(shè)置正則表達式選項的枚舉值。支持:None,Compiled,CultureInvariant,ECMAScript,ExplicitCapture,
IgnoreCase,IgnorePatternWhitespace,Multiline,RightToLeft,Singleline媒鼓。
MatchGroups函數(shù)格式與MatchGroup相似:
list MatchGroups(string,regexString,[Optional] groupNames,[Optional] regexOptions)
說明:
分組正則表達式匹配错妖,返回所有匹配結(jié)果。
對比案例1:未分組正則表達式
MatchGroup( "abc123def12344" , "[0-9]+")
輸出:123
MatchGroups( "abc123def12344" , "[0-9]+")
輸出:
[
"123", //第一組
"12344" //第二組
]
對比案例2:分組正則表達式潮模,未指定提取分組名稱
MatchGroup( "abc123def12344" , "(?<a1>[0-9]+)")
輸出:
{
"0": "123",
"a1": "123"
}
MatchGroups( "abc123def12344" , "(?<a1>[0-9]+)")
輸出:
[
{ //第一組
"0": "123", //系統(tǒng)默認痴施,未指定組名
"a1": "123"
},
{//第二組
"0": "12344", //系統(tǒng)默認,未指定組名
"a1": "12344"
}
]
對比案例3:分組正則表達式动遭,指定一個提取分組名稱
MatchGroup( "abc123:45def12344:78" , "(?<a1>[0-9]+):(?<b1>[0-9]+)","a1" )
輸出:123
MatchGroups( "abc123:45def12344:78" , "(?<a1>[0-9]+):(?<b1>[0-9]+)","a1" )
輸出:
[
"123", //第一組
"12344" //第二組
]
對比案例4:分組正則表達式神得,指定多個提取分組名稱
MatchGroup( "abc123:45def12344:78" , "(?<a1>[0-9]+):(?<b1>[0-9]+)","a1|b1" )
輸出:
{
"a1": "123",
"b1": "45"
}
MatchGroups( "abc123:45def12344:78" , "(?<a1>[0-9]+):(?<b1>[0-9]+)","a1|b1" )
輸出:
[
{//第一組
"a1": "123",
"b1": "45"
},
{ //第二組
"a1": "12344",
"b1": "78"
}
]
例1:
MatchGroup("關(guān)井油壓5.7MPa,套壓8.2MPa哩簿。", "油壓(?<P1>[0-9]+(\.[0-9]+){0,1})" ,"P1")
輸出:5.7
例2:
MatchGroup("關(guān)井油壓5.7MPa,套壓8.2MPa。", "油壓(?<P1>[1-9]\d*.\d*|0.\d*[1-9]\d*)[\s\S]*套壓(?<P2>[1-9]\d*.\d*|0.\d*[1-9]\d*)" ,"P1|P2")
輸出:
{
"P1": "5.7",
"P2": "8.2"
}
例3:
MatchGroup( "ftp://anonymous:guest@ftp.ncbi.nlm.nih.gov:21/gdgdsg/wrwq" , "(?<ftp>sftp|ftp)?://((?<username>\w+):(?<password>\w+)@)*(?<url>[.A-Za-z0-9]*)(:(?<port>[0-9]*))*(?<remotepath>/[\s\S]*)*","ftp|username|password|url|port|remotepath" )
輸出:
{
"ftp": "ftp",
"username": "anonymous",
"password": "guest",
"url": "ftp.ncbi.nlm.nih.gov",
"port": "21",
"remotepath": "/gdgdsg/wrwq"
}
后記:
MatchGroup函數(shù)配合“解析JSON”節(jié)點羡玛,分隔字段內(nèi)容宗苍。