user2188880
user2188880

Reputation: 21

Regex to find a string inside a couple of special characters

Hey guys i am trying to find a pattern in a string let's say this is my string

Hello World :this is what i am trying to detect: 

i am looking for a regex that matches anything that comes between

:"STRING":

i googled a bit and found some results, but nothing seems to be working. I successfully matched :test: but more than one word and it's breaking

this is the best answer i got

^[:]\\w+|(?<=\\s)[@#]\\w+

Upvotes: 1

Views: 432

Answers (3)

Mukesh Methaniya
Mukesh Methaniya

Reputation: 772

([:][A-Za-z0-9]+[:])

You can put more character in this range or directly use \s

Upvotes: 0

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10476

You can use that :

:(.*?):

Demo

Explanation:

  1. : looks for the first :
  2. .*? lazily matches everything until the next :
  3. : ends the matching

UPDATE:

If you want go beyond : and look for any special of the following group then you can try this:

[:#@]([^:#@]*?)[:#@]

Demo 2

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

The trick to matching between characters X is to match "everything except X" for the body of the message:

:[^:]*:

The expression means literally this:

  • A colon :
  • Followed by zero or more characters other than colon [^:]*
  • Another colon :

Upvotes: 2

Related Questions