regex search a string for contents between two strings

拥有回忆 提交于 2019-12-25 05:04:28

问题


I am trying my upmost best to get my head around regex, however not having too much luck.

I am trying to search within a string for text, I know how the string starts, and i know how the string ends, I want to return ALL the text inbetween the string including the start and end.

Start search = [{"lx":

End search = }]

i.e

[{"lx":variablehere}]

So far I have tried

/^\[\{"lx":(*?)\}\]/;

and

/(\[\{"lx":)(*)(\}\])/;

But to no real avail... can anyone assist?

Many thanks


回答1:


You're probably making the mistake of believing the * is a wildcard. Use the period (.) instead and you'll be fine.

Also, are you sure you want to stipulate zero or more? If there must be a value, use + (one or more).

Javascript:

'[{"lx":variablehere}]'.match(/^\[\{"lx":(.+?)\}\]/);



回答2:


The * star character multiplies the preceding character. In your case there's no such character. You should either put ., which means "any character", or something more specific like \S, which means "any non whitespace character".




回答3:


Possible solution:

var s = '[{"lx":variablehere}]';
var r = /\[\{"(.*?)":(.*?)\}\]/;
var m = s.match(r);

console.log(m);

Results to this array:

[ '[{"lx":variablehere}]',
  'lx',
  'variablehere',
  index: 0,
  input: '[{"lx":variablehere}]' ]



回答4:


\[\{"lx"\:(.*)\}\]

This should work for you. You can reach the captured variable by \1 notation.




回答5:


Try this:

    ^\[\{\"lx\"\:(.*)\}\]$

all text between [{"lx": and }] you will find in backreference variable (something like \$1 , depends on programming language).



来源:https://stackoverflow.com/questions/11032323/regex-search-a-string-for-contents-between-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!