Home > Mobile >  How to use Regex to find string between brackets that must contain a specific character?
How to use Regex to find string between brackets that must contain a specific character?

Time:10-12

I'm trying to find a solution to match these

#Find.Me Contain at least one dot#...Hey Hey #DontFindMe#

I need to find only the #Find.Me Contain at least one dot# phrase because it contain a "dot" ., the problem my current regex: \#(.*?)\# returns both of them: #Find.Me Contain at least one dot# and #DontFindMe#

How to change the regex to return only the #Find.Me Contain at least one dot#?

CodePudding user response:

You can use a negated character class:

#[^#.]*\.[^#]*#

Explanation

  • # Match literally
  • [^#.]* Optionally repeat matching any char except # or a dot
  • \. Match a dot
  • [^#]* Optionally repeat matching any char except #
  • # Match literally

Regex demo

CodePudding user response:

Maybe a bit tricky, but my thought is you want to check for an even number of '#' ahead too:

#[^#.]*\.[^#.]*#(?=(?:[^#]*#[^#]*#)*[^#]*$)

See an online demo


  • #[^#.]*\.[^#.]*# - Match exactly as you desire between two literal '#' with exactly a single dot;
  • (?= - Open a positive lookahead;
    • (?:[^#]*#[^#]*#)* - Match a non-capture group 0 times to match 0 '#' followed by balanced pairs of '#';
    • [^#]*$) - Match 0 '#' before end-line anchor.

CodePudding user response:

This should do:

#(.*?\..*?)#

https://regex101.com/r/84dxhG/1

If you want to make sure that # are delimiters:

#([^#]*\.[^#]*)#

https://regex101.com/r/qFpeFR/1

CodePudding user response:

I would recomend you some usefull sites, where you can test different expressions and see live what is slected.

Regex101

Regex

For accept this as an answer I Am enclosing one of possible solutions:

# *([^#] )

Which will select

#Find.Me Contain at least one dot#...Hey Hey #DontFindMe#

from sentence

RegExr solution

  • Related