简体   繁体   中英

How to match just the first number in Regex

I have this string

<h2 id="1">1. Item 1</h2>
<h2 id="1.2">1.2. Item 1.2</h2>
<h2 id="2">2. Item 2</h2>

I need to match headers which have int numbers 1. and 2. in the text. Not 1.2.

I do it like this

<h2.*?>(.*?)[0-9]\.\s+(.*?)</h2>

It matches all headers. Where am I wrong?

Remove (.*?) and then add a + after [0-9] because (.*?) exists before [0-9] will match any character zero or more times, which in-turn matches 1.

<h2.*?>[0-9]+\.\s+(.*?)</h2>

DEMO

您可以使用正则表达式:

<h[1-6][^>]*>\d{1}\.(?!\d{1}\.)([^<]*)<\/h[1-6]>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM