我有一个文档,我需要从中提取一些数据。文档包含如下在JavaScript正则表达式中积极寻找背后
Text:"How secure is my information?"
我需要提取的文字是在双引号中的字面Text:
How secure is my information?
后如何在Javascript
做到这一点与正则表达式我有一个文档,我需要从中提取一些数据。文档包含如下在JavaScript正则表达式中积极寻找背后
Text:"How secure is my information?"
我需要提取的文字是在双引号中的字面Text:
How secure is my information?
后如何在Javascript
做到这一点与正则表达式JavaScript正则表达式做字符串不支持lookbehinds。你必须使用捕获括号来代替:
var str = 'Text:"How secure is my information?"',
reg = /Text:"([^"]+)"/;
alert(str.match(reg)[1]);
// -> How secure is my information?
但是,如何从大文档中提取所有这些数据?请说出数组或其他内容? – Raj 2010-08-25 19:00:53
您可以使用/ g修饰符答案: – 2010-08-25 22:57:26
@Raj:你可以使用'/ g'修饰符,就像Crayon Violent所说的那样,这是全局修饰符,如果没有它,正则表达式会在找到第一个匹配时停止执行,正则表达式会一直持续到它找到所有匹配项,返回一个包含所有匹配项的数组 – 2010-08-26 08:21:05
你可以这样做:
/Text:"(.*?)"/
说明:
Text:"
:从字面上匹配.*?
:要匹配中的任何内容非贪婪方式()
:可以捕捉到比赛"
:要匹配文字"
/ /
:定界符你如何使用它?你有一些背景吗? – Sjoerd 2010-08-25 18:39:29
这是正则表达式,你应该使用它。例如.match() – 2010-08-25 22:56:53
<script type="text/javascript">
var str = 'Text:"How secure is my information?"';
var obj = eval('({'+str+'})')
console.log(obj.Text);
</script>
现代浏览器也有[JSON.parse](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/解析),这可能比'eval'更受欢迎。 – Sjoerd 2012-06-20 12:39:06
我只想补充一点:JavaScript的没有按” t支持向后看像(?<=)
或(?<!)
。
但它确实支持看起来像(?=)
或(?!)
。
如果你想避免正则表达式都在一起,你可以这样做:
var texts = file.split('Text:"').slice(1).map(function (text) {
return text.slice(0, text.lastIndexOf('"'));
});
这里是你展示如何接近这样一个例子。
1)鉴于这一输入字符串:
const inputText =
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;
2)字面Text:
后提取在双引号数据,以使得结果是,象这样所有比赛的数组:
["How secure is my information?",
"How to improve this?",
"OK just like in the \"Hackers\" movie."]
解决方案
function getText(text) {
return text
.match(/Text:".*"/g)
.map(item => item.match(/^Text:"(.*)"/)[1]);
}
console.log(JSON.stringify( getText(inputText) ));
RUN片段来看到一个工作演示
const inputText =
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;
function getText(text) {
return text
.match(/Text:".*"/g)
.map(item => item.match(/^Text:"(.*)"/)[1]);
}
console.log(JSON.stringify( getText(inputText) ));
那不是回顾后(甚至超前)。 – 2010-08-25 18:37:31
带有后视的正则表达式是怎样的? – inetphantom 2016-03-17 12:48:39
@MattBall,你怎么看?人们可以在一个或多个字符上匹配'Text:'的后视图,''和'''的前视图。 – henrebotha 2016-06-24 08:52:48