简体   繁体   English

如何只匹配正则表达式中的第一个数字

[英]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.我需要匹配文本中包含整数 1. 和 2. 的标题。 Not 1.2.不是 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.删除(.*?)然后在[0-9]之后添加一个+因为(.*?)[0-9]之前存在将匹配任何字符零次或多次,这反过来匹配1.

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

DEMO演示

您可以使用正则表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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