如何获取listbox控件对应条目的hh:mm格式时间索引
实现方案
你不需要拆分listbox的条目控件索引,直接对条目全文本做正则匹配即可提取目标时间,操作步骤如下:
步骤1:获取目标条目的完整文本
根据你使用的开发框架选择对应写法:
- C# WinForm:
string itemText = listBox1.SelectedItem.ToString(); - Python Tkinter:
item_text = listbox.get(listbox.curselection()) - 前端JS原生select控件:
const itemText = document.getElementById('listboxId').options[selectedIndex].text;
步骤2:正则匹配提取hh:mm格式时间
使用正则规则\b([01]?[0-9]|2[0-3]):[0-5][0-9]\b匹配合法的24小时制时间,可自动过滤非时间格式的冒号内容。
示例代码
C# 示例
using System.Text.RegularExpressions; string itemText = listBox1.SelectedItem.ToString(); Match timeMatch = Regex.Match(itemText, @"\b([01]?[0-9]|2[0-3]):[0-5][0-9]\b"); if (timeMatch.Success) { // 提取到的时间字符串,如10:58 string targetTime = timeMatch.Value; // 如果需要获取时间在条目中的字符索引,取timeMatch.Index即可 }
Python 示例
import re item_text = listbox.get(listbox.curselection()) time_match = re.search(r'\b([01]?[0-9]|2[0-3]):[0-5][0-9]\b', item_text) if time_match: # 提取到的时间字符串 target_time = time_match.group() # 如果需要获取时间在条目中的字符索引,取time_match.start()即可
内容的提问来源于stack exchange,提问作者Afonso Câmara
相关产品推荐
相关产品推荐

