在双引号之间选择特定字符的正则表达式

huangapple go评论86阅读模式
英文:

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

(?&lt;=\&quot;)(;)*(?=\&quot;)

Any idea ?
Thank you in advance

答案1

得分: 1

  1. 选择引号之间的所有部分:/&quot;[^&quot;]+&quot;/gm
  2. 在这些匹配中查找;

您应该能够在给定的正则表达式上使用 String.prototype.replace,并在替换回调中查找 &quot;;&quot;

这是一个演示:

function escapeCsvDelimiter(input) {
  return input.replace(/&quot;[^&quot;]+&quot;/gm, (match) => match.replace(/;/g, '\\;'));
}

const test = 'Lorem;ipsum;&quot;dolor;sit;&quot;;amet;&quot;jhv;&quot;';
const result = escapeCsvDelimiter(test);

console.log(result);
英文:

You will have to do it in two steps:

  1. select every parts between quotes: /&quot;[^&quot;]+&quot;/gm
  2. 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(/&quot;[^&quot;]+&quot;/gm, (match) =&gt; match.replace(/;/g, &#39;\\;&#39;));
}

const test = &#39;Lorem;ipsum;&quot;dolor;sit;&quot;;amet;&quot;jhv;&quot;&#39;;
const result = escapeCsvDelimiter(test);

console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月6日 20:24:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定