Python提取特定值求助:无法获取deviceID=100089
Hey there! I totally get how frustrating it is when your regex returns None when you know the value is there—especially when you're just starting out with Python and regex. Let's walk through the most common issues and fix this together.
First, Let's Cover the Basics
The None result means your regex pattern isn't matching anything in the string you pulled from the file. Here are the top reasons this happens, plus fixes for each scenario:
1. Your regex isn't accounting for whitespace
If your target string looks like deviceID = 100089 (with spaces around the equals sign) but your regex is r'deviceID=100089', it won't match. You need to allow for optional spaces with \s*:
import re # String from your file file_content = "Sample text with deviceID = 100089 and other details" # Pattern that allows optional spaces around = pattern = r'deviceID\s*=\s*(\d+)' match = re.search(pattern, file_content) if match: print(f"Found deviceID: {match.group(1)}") # Outputs 100089 else: print("No match found")
2. You used re.match instead of re.search
re.match only checks for matches at the start of the string. If your deviceID is somewhere in the middle of the text, use re.search instead—it scans the entire string for the pattern.
3. Your string has quotes around the deviceID
If the text looks like "deviceID": "100089" or 'deviceID': 100089, adjust your regex to include those quotes (note that numbers might be unquoted in JSON):
# For quoted key and value: pattern = r'"deviceID"\s*:\s*"(\d+)"' # For unquoted number (common in JSON): pattern = r'"deviceID"\s*:\s*(\d+)'
4. Bonus: Use JSON parser if the data is JSON-formatted
If the content from your file is valid JSON, you don't even need regex—using Python's built-in json module is more reliable:
import json with open('your_file.txt', 'r') as f: data = json.load(f) device_id = data.get("deviceID") print(f"Found deviceID: {device_id}") # Will get 100089 if it exists
Quick Checks to Verify
- Double-check that you're reading the entire file correctly: Use
f.read()instead off.readline()if the deviceID might be on a different line. - Print the string you're searching in first—sometimes the file content has unexpected characters (like newlines or tabs) that break the regex.
内容的提问来源于stack exchange,提问作者Addy

