我如何使用变量进行字符串精确匹配拆分?

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

How can I split a string with an exact match of a variable?

问题

我需要将字符串分割以移除任何精确匹配。

这是我尝试过的。

let str = 'a abc a a bac';
let m = 'a';
str.split(m);

结果将移除字符串中所有变量的出现。我需要一种方法将变量放入 /^$/ 正则表达式中,以仅获取精确匹配。有什么建议吗?

英文:

Basically, I need to split a string to remove any exact matches.

Here's what I tried.

let str = 'a abc a a bac';
let m = 'a';
str.split(m);

the result will remove all occurrences of the variable in the str. I need a way to put a variable inside a /^$/ regex to get only the exact matches. Any suggestions ?

答案1

得分: 0

这听起来像是您想要将输入分割为“单词”,然后筛选掉其中的一些单词。这可以通过使用split然后使用filter来实现:

const str = 'a abc a a bac';
const m = 'a';
const result = str.split(/\s+/).filter(x => x != m);
console.log(result);
英文:

It sounds like you want to split your input into "words", then filter out some of the words. This can be achieved by using split followed by filter:

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

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

const str = &#39;a abc a a bac&#39;;
const m = &#39;a&#39;;
const result = str.split(/\s+/).filter(x =&gt; x != m);
console.log(result);

<!-- end snippet -->

答案2

得分: 0

let str = 'a abc a a bac';
//根据您的要求将a存储在变量中
let m = 'a';
//我们需要使用变量形成正则表达式
//这个表达式匹配a与单词边界和空格,如果您想保留空格,只需删除|\s
let reg = new RegExp('\b' + m + '\b|\s', 'gm');
console.log(str.split(reg))

英文:
let str = &#39;a abc a a bac&#39;;
//as you asked a to be in variable
let m = &#39;a&#39;;
//we need to form RegEx with variable
//this expression matches a with word boundry and spaces if you wish to keep spaces just remove |\\s 
let reg = new RegExp(&#39;\\b&#39; + m + &#39;\\b|\\s/gm&#39;)
console.log(str.split(reg))

huangapple
  • 本文由 发表于 2023年6月12日 02:02:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451806.html
匿名

发表评论

匿名网友

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

确定