You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则表达式:精准提取字符串指定起始位置的目标内容问题

Fixing the Regex to Extract "random\string" from Your String

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 09:59:05