Skip to main content
karthikS
Inspiring
September 29, 2022
Answered

RegEx pattern in chapters numbers

  • September 29, 2022
  • 12 replies
  • 1405 views

Hi friends,

 

Please help on this.

I need to catch the below all chapters in the RegEx pattern.

 

I have try the this pattern - ((C|c)hapter(s)?[\s][0-9–]+[\s\,0-9&]*[and]{3,3}[\s0-9]+)|((C|c)hapter(s)?[\s][0-9–]+[\s\,0-9&]*) - not working properly.

 

Chapter 1

Chapters 1–6

Chapters 2 and 3

Chapters 2 & 3

Chapters 2, 3, 4

Chapters 2, 3, and 4

Chapters 2, 3 and 4

 

Thanks in Advance,

Karthik S

This topic is closed to new replies. Start a new post to keep the conversation going.
Correct answer Peter Kahrel

Nice one, Mark. For interest's sake, just a couple of small things. Your expression matches the space characters that follow numbers. And when you make optional whatever follows a single number, there's no need to repeat 'Chapter':

[Cc]hapters?\s\d+  // This is the minimum match
(((–|,\s|,?\s(&|and)\s)\d+)+)?   // Followed by any of these

 Peter

12 replies

Peter Kahrel
Community Expert
Peter KahrelCommunity ExpertCorrect answer
Community Expert
September 29, 2022

Nice one, Mark. For interest's sake, just a couple of small things. Your expression matches the space characters that follow numbers. And when you make optional whatever follows a single number, there's no need to repeat 'Chapter':

[Cc]hapters?\s\d+  // This is the minimum match
(((–|,\s|,?\s(&|and)\s)\d+)+)?   // Followed by any of these

 Peter

m1b
Community Expert
Community Expert
September 29, 2022

Excellent! Thanks Peter. 🙂

m1b
Community Expert
Community Expert
September 29, 2022

Hi @karthikS, here's what I came up with...

[Cc]hapters?\s\d+[,\-–\s]+(and|\&)?(\s?\d+[,\-–\s]+(and|\&)?)?\s?\d*

It's a bit of a brute force approach, but worked in my simple testing.

- Mark 

karthikS
karthikSAuthor
Inspiring
September 29, 2022

Hi Mark,

Thank you very much! the above pattern wrong catch some cases. It's possible to ignore this case?

 

1. chapter 1 and ==> (ingnore [and space character])

2. chapter 1, ==> (ingnore [comma space character])

3. Chapters 2, 3 and ==> (ingnore [and space character])

4. Chapter 1 & ==> (ingnore [& space character])

 

Thanks in Advance,

Karthik S

m1b
Community Expert
Community Expert
September 29, 2022

Right. How about this:

([Cc]hapter\s\d+|[Cc]hapters?\s([\d,\s\-–]|(and|\&)\s\d+)+)

- Mark