简体   繁体   中英

How to match between characters but not include them in the result

Say I have a string "&something=variable&something_else=var2"

I want to match between &something= and &, so I'll write a regular expression that looks like:

/(&something=).*?(&)/

And the result of .match() will be an array:

["&something=variable&", "&something=", "&"]

I've always solved this by just replacing the start and end elements manually but is there a way to not include them in the match results at all?

You're using the wrong capturing groups. You should be using this:

/&something=(.*?)&/

This means that instead of capturing the stuff you don't want (the delimiters), you capture what you do want (the data).

You can't avoid them showing up in your match results at all, but you can change how they show up and make it more useful for you.

If you change your match pattern to /&something=(.+?)&/ then using your test string of "&something=variable&something_else=var2" the match result array is ["&something=variable&", "variable"]

The first element is always the entire match, but the second one, will be the captured portion from the parentheses, which is much more useful, generally.

I hope this helps.

If you are trying to get variable out of the string, using replace with backreferences will get you what you want:

"&something=variable&something_else=var2".replace(/^.*&something=(.*?)&.*$/, '$1')

gives you

"variable"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM