解析字符串中的快速命令 Args: input_str: 输入字符串 Returns: Tuple[Optional[QuickCommand], str, Optional[int], Optional[str]]: (命令枚举, 去除命令的字符串, 数字参数, 警告信息) 如果解析成功: (命令, 文本, 数字, None) 如果解析失败: (None, 原字符串, None, 警告信息)
(input_str: str)
| 5 | |
| 6 | |
| 7 | def parse_quick_command(input_str: str) -> Tuple[Optional[QuickCommand], str, Optional[int], Optional[str]]: |
| 8 | """ |
| 9 | 解析字符串中的快速命令 |
| 10 | |
| 11 | Args: |
| 12 | input_str: 输入字符串 |
| 13 | |
| 14 | Returns: |
| 15 | Tuple[Optional[QuickCommand], str, Optional[int], Optional[str]]: |
| 16 | (命令枚举, 去除命令的字符串, 数字参数, 警告信息) |
| 17 | 如果解析成功: (命令, 文本, 数字, None) |
| 18 | 如果解析失败: (None, 原字符串, None, 警告信息) |
| 19 | """ |
| 20 | |
| 21 | # 获取所有命令值 |
| 22 | command_values = [cmd.value for cmd in QuickCommand] |
| 23 | |
| 24 | # 1. 检查字符串中是否包含任何命令 |
| 25 | found_commands = [] |
| 26 | for cmd_value in command_values: |
| 27 | # 使用正则表达式查找独立的命令(前后是单词边界或空格) |
| 28 | pattern = r'(?<!\S)' + re.escape(cmd_value) + r'(?!\S)' |
| 29 | if re.search(pattern, input_str): |
| 30 | found_commands.append(cmd_value) |
| 31 | |
| 32 | # 如果没有找到任何命令,直接返回原字符串 |
| 33 | if not found_commands: |
| 34 | return None, input_str, None, None |
| 35 | |
| 36 | # 2. 检查是否包含多个命令 |
| 37 | if len(found_commands) > 1: |
| 38 | return None, input_str, None, f"错误: 字符串中包含多个命令: {', '.join(found_commands)}" |
| 39 | |
| 40 | # 此时只有一个命令 |
| 41 | command_str = found_commands[0] |
| 42 | |
| 43 | # 3. 构建完整匹配模式,匹配命令及其后的可选数字 |
| 44 | # 模式: 命令 + 可选的空格 + 可选的数字 |
| 45 | full_pattern = r'(?<!\S)(' + re.escape(command_str) + r')(?:\s+(\d+))?(?!\S)' |
| 46 | match = re.search(full_pattern, input_str) |
| 47 | |
| 48 | if not match: |
| 49 | return None, input_str, None, f"错误: 命令格式不正确" |
| 50 | |
| 51 | command_part = match.group(1) |
| 52 | number_part = match.group(2) |
| 53 | |
| 54 | # 4. 检查命令是否在字符串末尾 |
| 55 | # 计算命令的结束位置 |
| 56 | command_end_pos = match.end() |
| 57 | |
| 58 | # 如果命令不在字符串的末尾(忽略尾部空格) |
| 59 | if command_end_pos < len(input_str.rstrip()): |
| 60 | # 检查命令后面是否有非空格字符 |
| 61 | remaining_text = input_str[command_end_pos:].strip() |
| 62 | if remaining_text: |
| 63 | return None, input_str, None, f"错误: 命令不在字符串末尾,命令后还有内容: '{remaining_text}'" |
| 64 |
no test coverage detected