英文:
Regex select specific characters between double quotes
问题
我想提取位于引号(")之间的特定字符,即 ;,并使用正则表达式来实现。
字符串示例:
> Lorem;ipsum;"dolor;sit;";amet;
应该选择引号内的每个 ;:
> Lorem;ipsum;"dolor;sit;";amet;
我尝试了以下正则表达式,但它不起作用:
(?<=\")(;)*(?=\")
有什么建议吗?
提前感谢您。
英文:
I would like to extract specific character i.e. ; that are located between quotes (") with a Regex expression.
<br/>
String example :
> Lorem;ipsum;"dolor;sit;";amet;
<br/>
Should select every ; in quotes :
> Lorem;ipsum;"dolor;sit;";amet;
<br/>
I tried this one but it doesn't work
(?<=\")(;)*(?=\")
Any idea ?
Thank you in advance
答案1
得分: 1
- 选择引号之间的所有部分:
/"[^"]+"/gm - 在这些匹配中查找
;
您应该能够在给定的正则表达式上使用 String.prototype.replace,并在替换回调中查找 ";"。
这是一个演示:
function escapeCsvDelimiter(input) {
return input.replace(/"[^"]+"/gm, (match) => match.replace(/;/g, '\\;'));
}
const test = 'Lorem;ipsum;"dolor;sit;";amet;"jhv;"';
const result = escapeCsvDelimiter(test);
console.log(result);
英文:
You will have to do it in two steps:
- select every parts between quotes:
/"[^"]+"/gm - in these matchs, search for
;
you should be able to use String.prototype.replace with the given regex and look for ";" in your replace callback.
here is a demo:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function escapeCsvDelimiter(input) {
return input.replace(/"[^"]+"/gm, (match) => match.replace(/;/g, '\\;'));
}
const test = 'Lorem;ipsum;"dolor;sit;";amet;"jhv;"';
const result = escapeCsvDelimiter(test);
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论