python - 如何使用正则表达式捕获 python 中两个连字符之间的单词?

标签 python regex pandas dataframe

我想提取两个连字符之间或一个连字符与空之间的单词。但是假设我不应该知道连字符之前/之间/之后的词。 我试过使用正则表达式模式进行 re.search。使用网站测试正则表达式时,捕获的组在 python 中不相同。

示例:

df = pd.DataFrame({'col1': ['tumPar-PredCorr', 'lung-Med-Pred', 'liver-t1flair-FromMed', 'kidney-t1ce-Pred', 'tumMed-Pred']})

新列中的结果应为:PredCorr、Med、t1flair、t1ce、Pred

在 python 中使用以下代码:


def extract_signals(row):
    if row!="":
        return re.search(r"([-^]\w+)",row).group()

df["signals"]= df["col1"].apply(extract_signals)

我几乎得到了结果,因为我有 -PredCorr、-Med、-t1flair、-t1ce、-Pred 因此,最好不要在这些词之前加上连字符。 请注意,正则表达式的那些模式在 python 中也给出了相同的结果:([-]\w+) 或 (-\w+)

非常感谢!

最佳答案

你可以使用

df['signals'] = df['col1'].str.extract(r'-([^-]+)(?:-|$)')

参见 regex demo .正则表达式匹配

  • - - 连字符
  • ([^-]+) - 第 1 组:-
  • 以外的一个或多个字符
  • (?:-|$) - - 或字符串结尾。

Python 测试:

>>> import pandas as pd
>>> df = pd.DataFrame({'col1': ['tumPar-PredCorr', 'lung-Med-Pred', 'liver-t1flair-FromMed', 'kidney-t1ce-Pred', 'tumMed-Pred']})
>>> df['col1'].str.extract(r'-([^-]+)(?:-|$)')
          0
0  PredCorr
1       Med
2   t1flair
3      t1ce
4      Pred

关于python - 如何使用正则表达式捕获 python 中两个连字符之间的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68571952/

相关文章:

python - 创建具有条件的多列

python - 使用 Pandas DataFrame 计算百分比

python - 如何编写接收字符串消息并返回带分页的字符串消息列表的函数

python - 字符串索引超出范围python 3.7

python - 如何在Python中使用__slots__转储对象的所有字段

python - 如何在 Python 中索引浮点值?

javascript - js字符串替换不起作用

任何单词的java正则表达式

regex - 如何匹配但排除递归模式中的定界符

python - Pandas 连续日期