删除所有文本,在第一个括号之前和最后一个括号之后的字符。

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

Remove all text, character before first bracket and after last bracket

问题

var string = '.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,'

如何删除第一个 { 之前和最后一个 } 之后的所有文本和字符?

我的期望结果是:

{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say }

并删除:.,.a,, and ,.x.b,

英文:

My string :

var string = '.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,'

How can i remove all text, character before first { and after last }?

My desired result :

{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say }

and remove : .,.a,, and ,.x.b,

Thank you

答案1

得分: 1

我们可以尝试以下正则表达式替换:

var string = '.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,';
var output = string.replace(/^[^{]+|[^}]+$/g, "");
console.log(output);

这里使用的正则表达式模式表示匹配:

  • ^ 从字符串的开头
  • [^{]+ 匹配一个或多个不是 { 的前导字符
  • |
  • [^}]+ 匹配一个或多个不是 } 的尾随字符
  • $ 在字符串的结尾
英文:

We can try the following regex replacement:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var string = &#39;.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,&#39;;
var output = string.replace(/^[^{]+|[^}]+$/g, &quot;&quot;);
console.log(output);

<!-- end snippet -->

The regex pattern used here says to match:

  • ^ from the start of the string
  • [^{]+ match one or more leading characters which are not {
  • | OR
  • [^}]+ match one or more trailing characters which are not }
  • $ at the end of the string

答案2

得分: 0

匹配的结果是:

{正确答案1:b。)Susan },{正确答案3:b。)她没有说}
英文:

By greedy behaviour, pattern

{.*}

matches

{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say }

huangapple
  • 本文由 发表于 2023年2月18日 13:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491312.html
匿名

发表评论

匿名网友

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

确定