Если наша дата находится сразу после косой черты, мы можем просто использовать это выражение:
.+\/(\d{4})(\d{2})(\d{2}).+
Затем, если необходимо, и мы хотим добавить больше границ, мы, безусловно, можем сделать это, например:
.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}).+
или:
^.+\/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\/.+$
Тест
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r".+\/(\d{4})(\d{2})(\d{2}).+"
test_str = "date file /20190529050003/folder "
subst = "\\1-\\2-\\3"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Если мы хотим получить все числа, мы можем использовать другое выражение:
.+\/(\d+)\/.+
Test
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r".+\/(\d+)\/.+"
test_str = "date file /20190529050003/folder "
subst = "\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
RegEx Circuit
jex.im визуализирует регулярные выражения:
