Tob*_*oby 5 python regex string replace pandas
使得更换不区分大小写似乎并不在下面的例子中(我要替换的效果JR。或小与JR):
In [0]: pd.Series('Jr. eng').str.replace('jr.', 'jr', regex=False, case=False)
Out[0]: 0 Jr. eng
Run Code Online (Sandbox Code Playgroud)
为什么?我有什么误解?
该case参数实际上是一种方便的替代指定flags=re.IGNORECASE. 如果替换不是基于正则表达式,则它与替换无关。
所以,当regex=True,这些是你可能的选择:
pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', regex=True, case=False)
# pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', case=False)
0 jr eng
dtype: object
Run Code Online (Sandbox Code Playgroud)
或者,
pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', regex=True, flags=re.IGNORECASE)
# pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', flags=re.IGNORECASE)
0 jr eng
dtype: object
Run Code Online (Sandbox Code Playgroud)
通过将不区分大小写标志作为模式的一部分,您还可以变得厚脸皮并绕过两个关键字参数?i。看
pd.Series('Jr. eng').str.replace(r'(?i)jr\.', 'jr')
0 jr eng
dtype: object
Run Code Online (Sandbox Code Playgroud)
注意
您需要\.在正则表达式模式下对句点进行转义,因为未转义的点是具有不同含义的元字符(匹配任何字符)。如果要在模式中动态转义元字符,可以使用re.escape.
有关标志和锚点的更多信息,请参阅文档和reHOWTO 的这一部分。
从源代码中可以明显看出,如果 ,“case”参数将被忽略regex=False。看
Run Code Online (Sandbox Code Playgroud)# Check whether repl is valid (GH 13438, GH 15055) if not (is_string_like(repl) or callable(repl)): raise TypeError("repl must be a string or callable") is_compiled_re = is_re(pat) if regex: if is_compiled_re: if (case is not None) or (flags != 0): raise ValueError("case and flags cannot be set" " when pat is a compiled regex") else: # not a compiled regex # set default case if case is None: case = True # add case flag, if provided if case is False: flags |= re.IGNORECASE if is_compiled_re or len(pat) > 1 or flags or callable(repl): n = n if n >= 0 else 0 compiled = re.compile(pat, flags=flags) f = lambda x: compiled.sub(repl=repl, string=x, count=n) else: f = lambda x: x.replace(pat, repl, n)
您可以看到case仅在if语句内部检查参数。
IOW,唯一的方法是确保regex=True替换是基于正则表达式的。