Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regex would detect if a string is part of a numbered list?

I am really struggling to find a regular expression that will reliably check to see if a string is part of a numbered list (such as those you would find in a common word-processor)

Therefore, I would like it to return true if the beginning of the string is a number followed by a fullstop and a space.

For single or even double digit numbers I can of course do this easily without the need for regular expressions, but since the number could be any size, it will not work.

Example 1

"1. This is a string"

Should return true because the string begins with: "1. "

Example 2

"3245. This is another string"

Should return true because the string begins with: "3245. "

Example 3

"This is a 24. string"

Should return false

Because there is no pattern matched at the beginning of the string... however...

Example 4

"3. This is 24. string"

Should still return true

I hope this is clear enough.

Thanks in advance for any help.

like image 519
Gordo Avatar asked Jan 13 '23 15:01

Gordo


2 Answers

It is a pretty simple regex. The following will find the start of the string, then a digit character repeated one or more time, then a period character, then the space character.

^\d+\. 

REY

In JavaScript you can do the following to test the string:

var startsWithNumber = /^\d+\. /m.test('34. this should return true.');

jsFiddle

like image 162
Daniel Gimenez Avatar answered Jan 30 '23 20:01

Daniel Gimenez


You could simply do..

/^\d+\.\s+/ or even /^\d*\.\s*/

Explanation of + and * operators

\d         Any digit
\s         Any whitespace character
*          Zero or more
+          One or more
like image 25
hwnd Avatar answered Jan 30 '23 18:01

hwnd