简体   繁体   English

匹配引号内的换行符

[英]Match newline characters inside quotes

I'm looking for a solution to replace the newline characters found inside an XML's attributes (XML string) in Javascript. 我正在寻找一种解决方案来替换Javascript中XML属性(XML字符串)中的换行符。 (Trying to replace with 
 so I do not lose newlines when parsing XML back) (尝试用
替换,因此在解析XML时我不会丢失换行符)

Note: There are other newlines in the string, eg after <main> .. </body> 注意:字符串中还有其他换行符,例如<main> .. </body>

(Open to any other regex/non-regex solutions!) (开放给任何其他正则表达式/非正则表达式解决方案!)

<main>
<head/><body><note text="Load"> 
<note text="2 Newlines at the end of this    

newline"/>
</body>
</main>

All I have is this awful thing "[\\s\\S]*?([\\r\\n]+)[\\s\\S]*?" 我只剩下这可怕的东西"[\\s\\S]*?([\\r\\n]+)[\\s\\S]*?"

https://regex101.com/r/vE2lD7/2 https://regex101.com/r/vE2lD7/2

Here is a little snippet making the conversion: 以下是进行转换的小片段:

 function convert(xmlStr) { var xml = document.createElement('xml'); xml.innerHTML = xmlStr; [].forEach.call(xml.querySelectorAll('note[text]'), function (note) { note.setAttribute('text', note.getAttribute('text').replace(/\\r?\\n/g,'@#10')); }); return xml.innerHTML.replace(/@#10/g, '&#10'); } // I/O var button = document.querySelector('button'); var input = document.querySelector('textarea'); var output = document.querySelector('pre'); // click handler button.onclick = function () { output.textContent = convert(input.value); } 
 textarea { width: 25em; height: 10em; float:left} 
 <textarea><main> <head/><body><note text="Load"> <note text="2 Newlines at the end of this newline"/> </body> </main></textarea> <button>convert</button> <pre></pre> 

Note that replacing with &#10 immediately would result the & to be escaped as &amp; 请注意,立即用&#10替换将导致&转为&amp; .

https://regex101.com/r/vE2lD7/3 https://regex101.com/r/vE2lD7/3

You want to alter the regex to not be greedy. 您想将正则表达式更改为不贪婪。 Here's a nice article describing it: 这是一篇描述它的好文章:

https://docs.oracle.com/javase/tutorial/essential/regex/quant.html https://docs.oracle.com/javase/tutorial/essential/regex/quant.html

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

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