正则表达式捕获两个字符串之间的字符串,多行 [英] Regex catch string between two strings, multiple lines

查看:88
本文介绍了正则表达式捕获两个字符串之间的字符串,多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理* .po文件,我试图捕获 msgid" msgstr" 之间的所有文本,不是很幸运,永远不要超过一行:

  msgid"即使您%s asdfgh asdsfgf asdfg%s毫无意义的asdfgdh句子.我们不是要翻译"莎士比亚的%s哈姆雷特%s!.%s测试了正则表达式%s"不需要特定的行业知识.享受"msgstr" 

我尝试过的事情:

  var myArray = fileContent.match(/msgid(["'])(?:(?=(\\?))\ 2.)*?\ 1/g); 

感谢您的帮助,我对regex并不是很好:(

解决方案

以下是提取所有文本的一种方法:

  var match = text.replace(/msgid"([[\ s \ S] *?)msgstr"/,"$ 1"); 

示例: http://jsfiddle.net/bqk79/

[\ s \ S] 是可与任何字符(包括换行符)匹配的字符类,因此 [\ s \ S] *?将与任何数字匹配任何字符.在其他语言中,可以使用 s DOTALL 标志使.匹配换行符,但Javascript不支持.

请注意,您的正则表达式没有提及单引号,但是如果您需要能够在 msgid'' msgstr 之间进行匹配您可以使用以下内容:

  var match = text.replace(/msgid(['] {2})([\ s \ S] *?)msgstr \ 1/," $ 2); 

I´m working on a *.po file, I´m trying to catch all the text between msgid "" and msgstr "", not really lucky, never more than one line:

msgid ""
"%s asdfgh asdsfgf asdfg %s even if you "
"asdfgdh sentences with no sense. We are not asking  translate "
"Shakespeare's %s Hamlet %s !. %s testing regex %s "
"don't require specific industry knowledge. enjoying "
msgstr ""

What I´ve tried:

var myArray = fileContent.match(/msgid ([""'])(?:(?=(\\?))\2.)*?\1/g);

Thanks for your help, I´m not really good with regex :(

解决方案

Here is one way to extract all of that text:

var match = text.replace(/msgid ""([\s\S]*?)msgstr ""/, "$1");

Example: http://jsfiddle.net/bqk79/

The [\s\S] is a character class that will match any character including line breaks, so [\s\S]*? will match any number of any character. In other languages you could use the s or DOTALL flag to make . match line breaks, but Javascript does not support this.

Note that you regex doesn't make any mention of single quotes, but if you need to be able to match between msgid '' and msgstr '' as well you can use the following:

var match = text.replace(/msgid (['"]{2})([\s\S]*?)msgstr \1/, "$2");

这篇关于正则表达式捕获两个字符串之间的字符串,多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆