拆分匹配模式的字符串 JavaScript
Split string matching a pattern JavaScript
我有一个 字符串 是这样的:
"First player vs. Second player     Percentage%"
第一位玩家和第二位玩家 可以是多个单词并且在[=17之前=]Percentage% 我正在使用三个  
。
我如何拆分此字符串以获得包含 First player 和 Second player 的数组(Percentage 不是必要)?
这应该可以满足您的要求:
const data=["First player vs. Second player     Percentage%",
"Another first player vs. a second one     Percentage%",
"One vs. Two    Two Percentage%"];
const res = data.map(s=>s.match(/(.+?)\s+vs\.\s+(.+?)\s*\ \ \ /).slice(1));
console.log(res)
在正则表达式中,我正在寻找两个匹配组 (.+?)
。这些是 non-greedy 匹配项,因为它们后面或前面有 \s+
(一个或多个白色 space 字符),我 不 想要这些我的匹配组中有白色space 个字符。
应该这样做
const test1 = 'First player vs. Second player Percentage&emsp'
const test2 = 'Ryu vs. Ken 100&emsp'
const extractPlayers= (string) => {
const [firstPlayer, rest] = string.split(' vs. ')
const secondPlayer = rest.split(' ').filter(x => x).slice(0, -1).join(' ').trim()
return {firstPlayer, secondPlayer}
}
console.log(extractPlayers(test1))
console.log(extractPlayers(test2))
我有一个 字符串 是这样的:
"First player vs. Second player     Percentage%"
第一位玩家和第二位玩家 可以是多个单词并且在[=17之前=]Percentage% 我正在使用三个  
。
我如何拆分此字符串以获得包含 First player 和 Second player 的数组(Percentage 不是必要)?
这应该可以满足您的要求:
const data=["First player vs. Second player     Percentage%",
"Another first player vs. a second one     Percentage%",
"One vs. Two    Two Percentage%"];
const res = data.map(s=>s.match(/(.+?)\s+vs\.\s+(.+?)\s*\ \ \ /).slice(1));
console.log(res)
在正则表达式中,我正在寻找两个匹配组 (.+?)
。这些是 non-greedy 匹配项,因为它们后面或前面有 \s+
(一个或多个白色 space 字符),我 不 想要这些我的匹配组中有白色space 个字符。
应该这样做
const test1 = 'First player vs. Second player Percentage&emsp'
const test2 = 'Ryu vs. Ken 100&emsp'
const extractPlayers= (string) => {
const [firstPlayer, rest] = string.split(' vs. ')
const secondPlayer = rest.split(' ').filter(x => x).slice(0, -1).join(' ').trim()
return {firstPlayer, secondPlayer}
}
console.log(extractPlayers(test1))
console.log(extractPlayers(test2))