【问题标题】:regex for replace words inside text by another words [duplicate]正则表达式用另一个单词替换文本中的单词[重复]
【发布时间】:2018-09-21 21:48:56
【问题描述】:

我有一个文本字符串,我想使用正则表达式将其替换为另一个文本

表示将每个单词替换为特定单词

input= Jounal Page Year DOI Roche-Link

我的预期输出

output = Publication Title Pagination Publication Date Digital Object Identifier Roche Link

用出版物标题替换期刊

分页替换页面

出版日期替换年份

DOI 替换为数字对象标识符

Roche-Link 替换为 Roche Link

  • 我的正则表达式=\b(Journal|Year|Page|DOI|Roche-Link)\b

我的正则表达式检测所有特定单词,但我没有找到使用$ 将每个单词替换为特定单词的解决方案

output = input.replace(/\b(Journal|Year|Page|DOI|Roche-Link)\b/g, (Publication Title)+$1, (Pagination)+$2,(Publication Date)+$3,(Digital Object Identifier)+$4,(Roche Link)+$5)

【问题讨论】:

  • 正则表达式因语言而异。当要求使用正则表达式时,请确保同时添加语言标签。
  • 我正在寻找使用 $ 将每个单词替换为特定单词的解决方案

标签: javascript regex


【解决方案1】:

你可以这样做:

var dict = {
  "Journal": "Publication Title",
  "Page":  "Pagination",
  "Year":  "Publication Date",
  "DOI": "Digital Object Identifier",
  "Roche-Link":  "Roche Link"
};

var regExp = new RegExp("\\b(" + Object.keys(dict).join("|") + ")\\b", "g");

var translated = "Journal Page Year DOI Roche-Link".replace(regExp, function(match) {
		return dict[match];
});

console.log(translated);

【讨论】:

  • 谢谢!但我正在寻找使用$ 将每个单词替换为特定单词的解决方案
猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多