简体   繁体   English

javascript正则表达式删除JSON查找字符串的开头和结尾部分

[英]javascript regex strip out beginning and end part around JSON looking string

Im hoping someone might be able to help with this. 我希望有人能够对此提供帮助。

Ive got a text file on the server loaded with the following 我在服务器上加载了以下文本文件

var templateCache = '{"templateCache":[  {"test":"123"}  ]}';

as its a text file, we are opening it and are aiming to strip out 作为文本文件,我们正在打开它,并打算去除

var templateCache = '----'; var templateCache ='----';

so we can convert the string into an object using JSON.stringify(). 因此我们可以使用JSON.stringify()将字符串转换为对象。

We are making use of Rhino.js as the server so we can only use vanilla JS functions to process this string into something usable for our app. 我们将Rhino.js用作服务器,因此我们只能使用香草JS函数将该字符串处理为可用于我们的应用程序的字符串。

Back story 背景故事

The file is included in the main function of our little app, but for us to manipulate this set of variables we are opening it, converting it into a JSON object and applying whats neccessary to it and then saving it back as the variable so it doesnt impact our app. 该文件包含在我们的小应用程序的主要功能中,但是对于我们来说,要操作这组变量,我们需要将其打开,将其转换为JSON对象,然后应用必要的内容,然后将其另存为变量,这样就不会影响我们的应用。 but I cant figure out how to strip out the var templateCache = ''; 但我不知道如何去掉var templateCache =''; and leave the middle content in place and im not sure what to look for via google to get the thing into order 并保留中间内容,我不确定要通过Google寻找什么以使事情井然有序

/var templateCache = '(.+)';$/m

The regex feature you are looking for is called 'capturing' . 您要查找的正则表达式功能称为“捕获” It's normally implemented with () parentheses in most languages, js included. 通常在大多数语言中都使用()括号来实现,包括js。

What this example regex does is it 'captures' and remembers everything between the () parentheses and makes it available for more processing. 这个正则表达式示例所做的是“捕获”并记住()括号之间的所有内容,并使其可用于更多处理。

Here's a quick example for your case: 这是您的情况的一个简单示例:

 var fileContent = 'var templateCache = \\'{"templateCache":[ {"test":"123"} ]}\\';' var regex = /var templateCache = '(.+?)';$/m; var matchedGroups = regex.exec(fileContent); console.log('Result String: ' + matchedGroups[1]); console.log(JSON.parse(matchedGroups[1])); 

Edit: changed the regex to handle cases where the file has more '; 编辑:更改了正则表达式以处理文件包含更多'; substrings on the same line after the json part. 子串位于json部分后的同一行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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