novalagung
novalagung

Reputation: 11502

regex find match between certain characters and contains specific character

So I have this text below:

#nama:sulaiman haqa#alamat:kepanjen#kelamain:L#hobi:tidur#

I need to find text between : and # that contains certain keyword. Example:

Search keyword: haq
result: sulaiman haqa

In example above, string sulaiman haqa fulfill the requirements: it's between : and # and also it has haq keyword.

I use this regular expression to find the word between : and #, but I don't know how to put the contains condition.

(?<=\:).*?(?=\#)

Please help.

Upvotes: 1

Views: 1009

Answers (3)

Emma
Emma

Reputation: 27723

Your expression is just fine, my guess is that you might only want to add a capturing group:

(?<=:)(.*haq.*?)(?=#)

so that to capture your desired values, and that'd likely solve the problem.

Demo

Upvotes: 0

anubhava
anubhava

Reputation: 784898

You may use this regex:

(?<=:)[^#]*haq[^#]*(?=#)

RegEx Demo

RegEx Details:

  • (?<=:): Lookbehind to assert that previous character is :
  • [^#]*: Match 0 or more of any character that is not #
  • haq: Match text haq
  • [^#]*: Match 0 or more of any character that is not #
  • (?=#): Lookahead to assert that next character is #

Upvotes: 4

Brett Zamir
Brett Zamir

Reputation: 14345

How about just this:

(?<=\:).*?haq.*?(?=\#)

You'd need to use your language's facilities to escape "haq" though in case it contained any special characters.

Upvotes: 2

Related Questions