1

I am using replace string using regex.

How will i find the following string with decimal number.

 Section 5.1.1
 Sections 5.1.2
 Sections 5.1.3 and 5.1.4
 Sec. 5.3.1

Can any one assist me?

Thanks in advance.

Updated:

 (Sec(?:s\.|s|tions|tion|.)?)( |\s)?((\w+)?([.-]|(–)|(—))?(\w+))(\s+)?((\w+)?([.-]|(–)|(—))?(\w+))(\s+(to|and|through)\s(\w+)([.-]|(–)|(—))(\w+))?
5
  • It depends on what you don't want to match, too... Should "Sect 666" be matched for example ? Commented Jun 17, 2015 at 12:14
  • Show us what you have tried. Commented Jun 17, 2015 at 12:17
  • see updated portion in my question Commented Jun 17, 2015 at 12:20
  • This big regex isn't made only for the cases you show. What's the problem with it ? Commented Jun 17, 2015 at 12:20
  • i am not able to get last three decimal digit after and. Commented Jun 17, 2015 at 12:22

1 Answer 1

2

How about

/(^|\s)(Sec\.|Sections?) +[0-9]+(\.[0-9]+)*( +and +[0-9]+(\.[0-9]+)*)*(?=$|\s)/

It will match substrings that

  • begin with whitespace or are at the beginning of the searched string
  • are followed by whitespace or are at the end of the searched string
  • start with Sec., Section or Sections
  • followed by one or more spaces
  • followed by a section number
  • optionally followed by one or more and [section number], where and is surrounded by one or more spaces.

Section numbers match if they

  • start with one or more digits
  • optionally followed one or more times by a dot and again one or more digits.

You can trim the match to get rid of eventual whitespace at the beginning of the match.

Update

/(^|[^\w])(Sec\.|Sections?) +[0-9]+(\.[0-9]+)*( +and +[0-9]+(\.[0-9]+)*)*(?=$|[^\w])/

This one matches substrings that

  • begin with a non-word character or are at the beginning of the searched string
  • are followed by a non-word character or are at the end of the searched string

Rest same as above. Use an additional replace on the match to get rid of non-word character matches at the beginning: match.replace(/^[^\w]+/, '')

Sign up to request clarification or add additional context in comments.

2 Comments

It is working fine. But if there is dot or comma at the end of the section. The match is not found. If i have dot or comma at the end of the section string, how will handle?
See updated answer. Please upvote/accept answer if it's what you were looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.