我才知道Shortest的这个“最短”并不是语义上的最短啊
mathematica吧
全部回复
仅看楼主
吧务
level 15
xzcyr 楼主
考虑下面这个例子:
str = "AbcAde" ;
StringCases[str, "A" ~~ Shortest[a__] ~~ "e" :> a]
会出现这种现象,是因为匹配是从左往右进行的,模式"A" ~~ Shortest[a__] ~~ "e"最先匹配到了最左端的A。也就是说,这个“最短”的寻找会以“包含最左端的A”为前提,“不包含最左端A”的情况则不在考虑之列。
此问题可参考SE帖子《Wrong result from StringCases with Shortest》(mathematica.stackexchange.com/a/72293/1871)
顺便,SequenceReplace也有类似行为:
lst = {A, b, c, A, d, e};
SequenceReplace[lst, {A, Shortest[a__], e} :> a]
2023年06月03日 03点06分 1
吧务
level 12
看来以后要写成
StringCases[str, ___ ~~ "A" ~~ Shortest[a__] ~~ "e" ~~ ___ :> a]
2023年06月03日 04点06分 2
这样无法多次匹配,比如 str = "AbcAde AbcAde"
2023年06月03日 07点06分
吧务
level 12
正则匹配里也是一样的规则,解决方法也很简单,加个Except就可以了
str = "AbcAde";
StringCases[str, "A" ~~ Shortest[a__] ~~ "e" :> a]
StringCases[str, "A" ~~ Shortest[a : Except["A"] ..] ~~ "e" :> a]
StringCases["AbcAde", RegularExpression["A(.+?)e"] :> "$1"]
StringCases["AbcAde", RegularExpression["A([^A]+?)e"] :> "$1"]
2023年06月03日 10点06分 3
吧务
level 13
对于更一般的情况
str = "prefix a prefix b suffix c suffix prefix d prefix e suffix f suffix"
匹配出 " b " 和 " e ",其中 b 和 e 代表不包含 prefix 和 suffix 的任意字符串,这种无法使用 Except
StringCases[str,
"prefix" ~~ Shortest[a__] ~~ "suffix" /; !
StringContainsQ[a, "prefix"] :> a]
StringCases[str,
RegularExpression["(?<=prefix)(?:.(?<!prefix))+?(?=suffix)"]]
2023年06月03日 10点06分 4
1