请求用于检测字符串中项目编号(含标题与子标题)的正则表达式
Hey there! Let's build the regex you need to detect those list item numbers (including both top-level and subheadings) based on your examples.
First, let's break down the patterns we need to cover:
- Numeric numbers with or without a trailing dot (like
1.or1) - Asterisk bullet points (
*) - Multi-level numeric numbers (like
1.1or2.1)
Here's a flexible regex that can match all these cases, accounting for possible leading whitespace (since lists are often indented):
^\s*(?:(\d+(?:\.\d+)*\.?|\*)\s+)
Let me break down what each part does:
^\s*: Matches any leading whitespace at the start of a line (handles indented lists)(?:...): A non-capturing group to group our different numbering patterns together\d+(?:\.\d+)*\.?: This covers numeric numbers:\d+: Matches one or more digits (the main number)(?:\.\d+)*: Optional repeated groups of a dot followed by digits (handles multi-level like1.1,1.1.2, etc.)\.?: Makes the trailing dot optional (so it matches both1and1.)
|: The "or" operator to include the asterisk pattern\*: Matches the asterisk bullet point
\s+: Matches one or more whitespace characters after the number/bullet (separating it from the content)
If you want to capture the actual number/bullet itself (instead of just detecting it), you can convert the non-capturing group to a capturing group by removing the ?::
^\s*((\d+(?:\.\d+)*\.?|\*)\s+)
Let's test this against your examples:
- For
1. Hello 2. World: It will match1.and2. - For
1 Hello 2 World: It will match1and2 - For
* Hello * World: It will match*and* - For
1 Hello1 1.1 Word1 2 Hello2 2.1 World2: It will match1,1.1,2, and2.1
One quick note: This regex assumes the list items start at the beginning of a line (or with indentation). If you need to match numbers anywhere in a string (not just line starts), you can remove the ^ anchor.
内容的提问来源于stack exchange,提问作者Ibrar Ahmed

