Creating fuzzy matching exceptions with Python's new regex module

孤者浪人 提交于 2019-12-19 09:41:18

问题


I'm testing the new python regex module, which allows for fuzzy string matching, and have been impressed with its capabilities so far. However, I've been having trouble making certain exceptions with fuzzy matching. The following is a case in point. I want ST LOUIS, and all variations of ST LOUIS within an edit distance of 1 to match ref. However, I want to make one exception to this rule: the edit cannot consist of an insertion to the left of the leftmost character containing the letters N, S, E, or W. With the following example, I want inputs 1 - 3 to match ref, and input 4 to fail. However, using the following ref causes it to match to all four inputs. Does anyone who is familiar with the new regex module know of a possible workaround?

input1 = 'ST LOUIS'
input2 = 'AST LOUIS'
input3 = 'ST LOUS'
input4 = 'NST LOUIS'


ref = '([^NSEW]|(?<=^))(ST LOUIS){e<=1}'

match = regex.fullmatch(ref,input1)
match
<_regex.Match object at 0x1006c6030>
match = regex.fullmatch(ref,input2)
match
<_regex.Match object at 0x1006c6120>
match = regex.fullmatch(ref,input3)
match
<_regex.Match object at 0x1006c6030>
match = regex.fullmatch(ref,input4)
match
<_regex.Match object at 0x1006c6120>

回答1:


Try a negative lookahead instead:

(?![NEW]|SS)(ST LOUIS){e<=1}

(ST LOUIS){e<=1} matches a string meeting the fuzzy conditions placed on it. You want to prevent it from starting with [NSEW]. A negative lookahead does that for you (?![NSEW]). But your desired string starts with an S already, you only want to exclude the strings starting with an S added to the beginning of your string. Such a string would start with SS, and that's why it's added to the negative lookahead.

Note that if you allow errors > 1, this probably wouldn't work as desired.



来源:https://stackoverflow.com/questions/14691908/creating-fuzzy-matching-exceptions-with-pythons-new-regex-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!