skip to Main Content

i’m trying to match words with enclosed brackets without inner spaces with this regex:
/(?<={{).*?(?=}})/g

some examples like: {{ test }} {{test}} {{ test}} {{test }}
but my regex takes out string with its white space that i don’t want it. like [space]test[space] [space]test test[space]

I want strings without any white space before and after of them. that all of them return `test`.

2

Answers


  1. Try this:

    /(?<={)w+(?=})/g

    All you need is a positive lookbehind (?<={) and lookahead (?=}). Then make sure there are characters (and no spaces) in between using w+:

    Login or Signup to reply.
  2. If you want to match word "test" without surrounding spaces in all four examples, you can use following regex:

    (?<={{s*)(?=S).*?(?=s*}})
    

    Here:

    • (?<={{s*) checks that match is preceded by {{ and any number of whitespaces,
    • (?=S) checks that match begins with something other than space,
    • .*? matches any symbols, smallest possible amount,
    • (?=s*}}) checks that match is followed by any number of whitespaces and }}.

    Demo here.

    Notice, if it is guaranteed that your brackets contain at least one nonwhitispace symbol, use (?<={{s*)S.*?(?=s*}}) instead, as it should have better performance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search