如何用正则表达式筛选以数字0开头的完整空格分隔序列?
Solution to Match Full Space-Separated Strings Starting with 0
The issue with your current regex r'\b0\S*' is that it matches any 0 that follows a word boundary—including 0 characters that are part of a larger comma-separated sequence within a space-separated entry (like the 0 in 1,0,39). To target only full space-separated entries that start with 0, use this adjusted regex:
import re x = '1,1,1075 1,0,39 2,4,1,22409 0,1,1,755,300 0,1,1,755,50' result = re.findall(r'(?<!\S)0\S+', x) print(result)
Output:
['0,1,1,755,300', '0,1,1,755,50']
How This Works:
(?<!\S): This is a negative lookbehind assertion that ensures the0is preceded by either the start of the string or a whitespace character. This rules out0s that are part of an existing comma-separated sequence (like the0in1,0,39, which is preceded by a comma, not whitespace/start).0: Matches the literal0that starts our target entry.\S+: Matches all non-whitespace characters following the0, capturing the entire comma-separated sequence until the next whitespace or end of string.
Why Your Original Regex Failed:
The \b word boundary matches between a non-word character (like ,) and a word character (like 0). So it incorrectly picked up 0,39 from the entry 1,0,39 because the comma creates a word boundary before the 0. The negative lookbehind fixes this by ensuring we only match 0s that start a new space-separated entry.
内容的提问来源于stack exchange,提问作者mikeL
相关产品推荐
相关产品推荐

