繁体   English   中英

查找字符串是否包含带有数字的子字符串,与另一个子字符串有一定距离

[英]Find if a string contains substring with a number, some distance from another substring

我有一个像

s = 'ahlkhsa-anchorawO&B6o77ooiynlhwlkfnbla,)9;}[test:""ajanchorkh,2Yio98vacpoi [p{7}]test:"2"*iuyanchorap07A(p)a test:""*^g8p9JiguanchorLI;ntest:"9.3"'

我想看看是否存在子字符串test:"some_number_here"anchor后最多 5 个字符

所以在这种情况下, test:"9.3"是在其他 5 个字符之后的子字符串anchor

还有test:"2"但是离它前面的anchor太远了,不想算了。

(如果我能在test:""

你可以试试

anchor.{,5}test:"([\d.]+)"
anchor            // literally "anchor"
.{,5}             // any character, repeats up to 5 times
test:"([\d.]+)"   // test:"digits and dots", the digits and dots are captured in group 1

该号码在第 1 组中捕获,请参阅测试用例

查看有关正则表达式量词的更多信息

  • 在 Python 中使用它:
import re

s = 'ahlkhsa-anchorawO&B6o77ooiynlhwlkfnbla,)9;}[test:""ajanchorkh,2Yio98vacpoi [p{7}]test:"2"*iuyanchorap07A(p)a test:""*^g8p9JiguanchorLI;ntest:"9.3"'

res = re.findall(r'anchor.{,5}test:"([\d.]+)"', s)

print(res)  # ['9.3']
  • 笔记

数字匹配松散, test:"." 也很重要。 如果你想要更严格的数字验证,你可以尝试anchor.{,5}test:"(?.\??")(\d*(:.\?\d*)?)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM