我使用一个子字符串函数从一个较长的字符串(duh)中获取我需要的特定子字符串
假设我的字符串是:“(..)partijen waarvan de下四分位0,68%bedraagt en de上四分位2,06%”
我追求的是大胆的价值观。现在,以下两个功能可以完美地工作:
content_higher = content_conclusion[content_conclusion.index("upper quartile"):content_conclusion.index("%.")]
content_lower = content_conclusion[content_conclusion.index("lower quartile"):content_conclusion.index("%")]
如您所见,对于“上四分位”(这是Transfer pricing/tax related),%字符后面跟着一个点(.),因为字符串在这里结束
当我将函数更改为查找上四分位值为下四分位值时,该函数不再工作:
content_higher = content_conclusion[content_conclusion.index("upper quartile"):content_conclusion.index("%")] #i.e., without the dot (.) that follows the % character
我理解这可能是因为这个%符号总是直接(即没有空格)后跟一个点(.)。但是,是否可以忽略以下字符。 我希望能够搜索特定的字符/子字符串,而不管该子字符串后面紧接着什么
换句话说,我可以使用通配符在特定字符上生成子字符串
希望以上是清楚的。非常感谢您的投入
可以使用Python正则表达式来实现这一点
参考:https://docs.python.org/3/howto/regex.html
我想出了下面的解决办法
一种选择是在匹配数字后使用以单词边界结尾的模式
b
防止部分匹配的单词边界(?:lower|upper) quartile
匹配其中一个备选方案,然后quartile
\d+(?:,\d+)?
将1+个数字与可选的小数部分匹配\b
单词边界见aregex demo或aPython demo
输出
相关问题 更多 >
编程相关推荐