Python正则表达式:精准提取字符串指定起始位置的目标内容问题
Got it, let's work through this regex problem. Your current pattern (?<=A ).+\s uses greedy matching, which means it'll grab everything up to the last whitespace in the string—way more than you need. Here are two straightforward solutions to get exactly "random\string":
Solution 1: Non-Greedy Matching with Positive Lookahead
Use a non-greedy quantifier .+? combined with a positive lookahead (?=\s) to stop matching right before the next whitespace:
import re # Use raw string to preserve the backslash, or double-escape it text = r"A random\string here" test = re.findall(r'(?<=A ).+?(?=\s)', text) print(test) # Output: ['random\\string']
How it works:
(?<=A ): Positive lookbehind to ensure we start right after"A ".+?: Non-greedy match of one or more characters (stops as soon as possible)(?=\s): Positive lookahead to stop when we hit the next whitespace character
Solution 2: Match Non-Whitespace Characters Directly
Since your target string "random\string" has no whitespace, we can just match all non-whitespace characters after "A " using \S+:
import re text = r"A random\string here" test = re.findall(r'(?<=A )\S+', text) print(test) # Output: ['random\\string']
How it works:
\S: Matches any non-whitespace character (including backslashes, letters, numbers, etc.)+: Matches one or more of the preceding character, so it grabs all consecutive non-whitespace content right after"A "
Important Note:
Watch out for the backslash in your original string! If you write "A random\string here" without using a raw string (r"") or escaping the backslash ("\\"), Python will interpret \s as a whitespace character. That means your actual string would be "A random string here", and your result would be "random string" instead of "random\string". Always use raw strings for regex patterns and strings containing literal backslashes to avoid unexpected behavior.
内容的提问来源于stack exchange,提问作者Pen7865

