简体   繁体   English

字符串正则表达式:从部分字符串中删除方括号

[英]String regex: Remove square brackets from part of the string

In JavaScript application I need to edit string.在 JavaScript 应用程序中,我需要编辑字符串。

Text comes with this structure:文本带有这种结构:

  • It may start with a prefix in square brackets [prefix] .它可以以方括号[prefix]中的前缀开头。 I need to keep this prefix with brackets.我需要用方括号保留这个前缀。
  • Second comes [whatever string], but this time I only need to keep string within brackets其次是 [whatever string],但这次我只需要将字符串保持在括号内

Example 1:示例 1:

[prefix][My title] [前缀][我的标题]

Returns: [prefix] My title返回:[前缀] 我的头衔

Example 2示例 2

[Another title without prefix] [另一个没有前缀的标题]

Returns: Another title without prefix返回:另一个没有前缀的标题

This will help you identify any text that is inside brackets这将帮助您识别括号内的任何文本

const keyRegex = /(?<=\[)(.*?)(?=\])/gmdi

With this try to use Regex.exec() from here .尝试使用此处的 Regex.exec() 。 Following the example from Mozilla developers you could check if array1[0] is equal with prefix or not.按照 Mozilla 开发人员的示例,您可以检查 array1[0] 是否等于前缀。 Happy coding快乐编码

Usually more "elegant" code is hard to understand even by future you (can't use comments yet )通常更“优雅”的代码即使是未来的你也很难理解(还不能使用注释)

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

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