简体   繁体   中英

Python3 RE match characters or no characters at end of line

I have a line of text that I need to pull a substring from that may or may not have characters following the substring. Examples:

Robin Hood viewed item "something.mov" (99.12345.567891011)

or...

Robin Hood viewed item "something.mov" (88.123.456789101) some other stuff.

I need to pull the substring that is inside the parentheses. The substring will always be three sets of digits separated by two periods. The string in quotes with the .mov at the end can also include arbitrary characters so the search should always start at the end of the line.

If there are characters after the closing paren then there will be a . at the end of the line. If there are no characters following the closing paren then there will be no . at the end of the line.

Right now I have:

mo = re.search(r'(\d[\d.]*)\).*$', data1)

However, this breaks on some matches. The problem is that the tool I'm using (Matillion) does not spit out the lines it fails on so I don't know why.

经过进一步的调查,我发现在我要查找的子字符串之后,子字符串中永远不会有括号,因此我只使用str.rfind()隔离了我想要的东西。

It seems like this should work:

mo = re.search(r'\((\d+\.\d+\.\d+)\)'), data1);

This matches an opening parentheses, 3 sets of digits separated by . , and a close parentheses. The sets of digits will be in capture group 1.

If you only want to match the last set of parentheses on the line, you can use:

mo = re.search(r'\((\d+\.\d+\.\d+)\)[^()]*$'), data1);

[^()]*$ ensures that there are no more parentheses between this set and the end of the line.

This regex should work: .*\\((\\d+\\.\\d+\\.\\d+)\\) .

I have added a prefix that consumes any characters before the next group, so all characters before the last occurrence of \\((\\d+\\.\\d+\\.\\d+)\\) will be ignored. This asserts the position at the end of the line in a different way than $ .

https://regex101.com/r/vuED26/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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