英文:
Regex: The word must have an apostrophe at the beginning and at the end ("word")
问题
I currently have the following program that uses a regular expression:
const regex = /[\s]|('[^']')|[\w-]+|[']/gm;
When running:
console.log("'one 'two' three'".match(regex) || []);
I get:
[
"'",
"one",
" ",
"'",
"two",
"'",
" ",
"three",
"'"
]
I need to update the regular expression in a way that I can get at the end:
[
"'",
"one",
" ",
"'two'",
" ",
"three",
"'"
]
英文:
I currently have the following program that uses a regular expression:
const regex = /[\s]|('[^']')|[\w-]+|[']/gm;
When running:
console.log("'one 'two' three'".match(regex) || []);
I get:
[
"'",
"one",
" ",
"'",
"two",
"'",
" ",
"three",
"'"
]
I need to update the regular expression in a way that I can get at the end:
[
"'",
"one",
" ",
"'two'",
" ",
"three",
"'"
]
答案1
得分: 1
You missed +
inside your quoted pattern.
\s|('[\w-]+')|[\w-]+|'
console.log("'one 'two' three'".match(/\s|('[\w-]+')|[\w-]+|'/gm) || []);
// Array(7) [ "'", "one", " ", "'two'", " ", "three", "'" ]
Also I've changed it to match only word symbols and minuses (by analogy with the next pattern), to exclude matching of 'one '.
If matching of phrases in quotes (like 'abc abc') is expected you could use \s|('(?=[\S])[^']+?(?<=\S)')|[\w-]+|'
EDIT: according to corrected input by OP, to allow words containing 's, like 'that's':
\s|((?<=\s|^)'[\w-][\w'-]*[\w-]'(?=\s|$))|[\w-][\w'-]*[\w-]|'|w
英文:
You missed +
inside your quoted pattern.
\s|('[\w-]+')|[\w-]+|'
console.log("'one 'two' three'".match(/\s|('[\w-]+')|[\w-]+|'/gm) || []);
// Array(7) [ "'", "one", " ", "'two'", " ", "three", "'" ]
Also I've changed it to match only word symbols and minuses (by analogy with next pattern), to exclude matching of 'one '
.
If matching of phrases in quotes (like 'abc abc'
) is expected you could you could use \s|('(?=[\S])[^']+?(?<=[\S])')|[\w-]+|'
EDIT: according to corrected input by OP, to allow words containing '
, like that's
:
\s|((?<=[\s|^])'[\w-][\w'-]*[\w-]'(?=\s|$))|[\w-][\w'-]*[\w-]|'|\w
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论