简体   繁体   English

正则表达式JS。 每个点的新行,但仅在引号之外

[英]Regex JS. New line for each dot, but only outside of a quotation

This is very strong for me. 这对我来说非常强大。 I give up, after two days, I ask you 我放弃了,两天后,我问你

Turn this 转这个

var str = 'The quick "brown. fox". jumps over. "the lazy dog"'
var str2 = 'The quick «brown. fox». jumps over. «the lazy dog»'

Into this 入这个

The quick "brown. fox".
jumps over.
"the lazy dog"

or 要么

The quick «brown. fox». 
jumps over. 
«the lazy dog»

In other words I would like to wrap every dot, but this should not happen if the dot is inside a quote 换句话说,我想包装每个点,但是如果点在引号内,则不会发生这种情况

Thanks 谢谢

You can use this lookahead based regex: 您可以使用以下基于前瞻的正则表达式:

var re = /(?=(([^"]*"){2})*[^"]*$)\./g;
var r;

r = str.replace(/(?=(([^"]*"){2})*[^"]*$)\./g, '.\n');
 The quick "brown. fox".
 jumps over.
 "the lazy dog"

r = str2.replace(re, '.\n');
 The quick «brown.
 fox».
 jumps over.
 «the lazy dog»

(?=(([^"]*"){2})*[^"]*$) is a lookahead that makes sure there are even number of quotes following dot thus making sure dot is outside the quotes. However note that quotes should be balanced and unescaped. (?=(([^"]*"){2})*[^"]*$)是先行的,它确保点后的引号数量是偶数,从而确保点在引号之外。但是请注意,报价应保持平衡且不转义。

Another aproach (like in JavaScript : Find (and Replace) text that is NOT in a specific HTML element? ), this could be solved by matching both, the quoted string and the desired period. 另一个方法(例如JavaScript中的:查找(和替换)不在特定HTML元素中的文本? ),可以通过将引用的字符串和所需的时间段进行匹配来解决。

In the replace-function you then have the chance to change only the single periods... 然后在替换功能中,您将有机会仅更改单个期间...

txt.replace(/("[^"]*"|«[^»]*»)|(\.)/g, function (_, quoted, dot) {
    if (quoted) return quoted;
    return '.\n';
});

With match 与比赛

str.match(/((?:"[^"]*"|«[^»]+»|[^".«]+)+(?:\.|$))\s*/g).join("\n")

"The quick "brown. fox". 
jumps over. 
"the lazy dog""

str2.match(/((?:"[^"]*"|«[^»]+»|[^".«]+)+(?:\.|$))\s*/g).join("\n")

"The quick «brown. fox». 
jumps over. 
«the lazy dog»"

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

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