[英]How to get substring(s) of a string if said substring(s) are between two specific characters
我想知道如何从字符串中提取单词(子串),如果所述字符串在两个特定字符之间。 在我的情况下,我正在寻找一个白色空间的起始角色,最后一个角色是这样的逗号:
var str = "Hit that thing man! and a one, two, three, four, five, six, seven or eight";
结果:
var result = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
我想知道正则表达式是否可行,或者好的旧javascript将是直接的解决方案。
到目前为止,我已尝试过以下内容:
var result = str.split(/[,\s]+/);
但无济于事,因为它不正确地执行以下行为:
one
之前抓住整个字符串。 奖金回合 :我可以通过添加到所需的正则表达式/ javascript解决方案,在结果中包含最后一个字母eight
吗?
任何帮助非常感谢!
TLDR: regex101.com
为什么不直接获得所有比赛 ? 这似乎比拆分东西简单。
var re = /(?:^|\s)([^,\s]+)(?:,|$| or)/g,
s = "Hit that thing man! and a one, two, three, four, five, six, seven or eight",
m,
matches = [];
// Matches once and then as long as there are some matches
do {
m = re.exec(s);
if (m) {
matches.push(m[1]);
}
} while (m);
console.log(m);
这会产生:
["one", "two", "three", "four", "five", "six", "seven", "eight"]
如果你不想匹配or
,只是将其删除:
/(?:^|[\s])([^,\s]+)(?:,|$)/g
而且你也可以添加and
经常出现而不是或在这样的列表中:
/(?:^|[\s])([^,\s]+)(?:,|$| and| or|)/g
^
和$
允许在字符串的开头和结尾匹配。
最终or
唯一的实际问题,因为JavaScript不支持lookbehinds。 出于这个原因,你不能使用单个正则表达式来捕获“两个特定字符之间”的单词 - 你总是最终得到结果中的左边一个。
我想出了这个:通过替换or
使用逗号将字符串变为形式并将其添加到结尾。 然后它是一个简单的正则表达式:
var result = str.concat(',').replace(' or ',',').match(/\w+(?=,)/g);
它不适用于split
因为这会将句子的整个第一部分分配给one
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.