Zacharia Mwangi
Zacharia Mwangi

Reputation: 53

Regex Match string if it exists

Example 1:

THE COMPANIES ACT 
(Cap 486)
IT IS notified 

Example 2:

THE COMPANIES ACT
(Cap. 486)
Incorporations
IT IS notified 

My current regex: THE COMPANIES ACT\n\(((?:Cap.|Cap) .*?)\)(?:\nIncorporations|\nincorporations)\nIT IS notifiedonly matches Example 2.

I would like it to match both examples.

Upvotes: 0

Views: 2490

Answers (1)

nicael
nicael

Reputation: 18995

You should make (?:\nIncorporations|\nincorporations) optional by appending ? (0 or 1 match) after it. Otherwise, the first example doesn't match as you have specified that you want to match (?:\nIncorporations|\nincorporations) in any case.

As ncorporations is common in both *ncorporations, you could consider (?:\n[Ii]ncorporations)? instead of (?:\nIncorporations|\nincorporations)? and (?:Cap\.?) instead of (?:Cap.|Cap), to shorten it a bit and also to escape the dot (since . means any character).

Upvotes: 4

Related Questions