正则表达式: 这个单词必须以撇号开头和结尾 (“word”)

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

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|(&#39;[\w-]+&#39;)|[\w-]+|&#39;
console.log(&quot;&#39;one &#39;two&#39; three&#39;&quot;.match(/\s|(&#39;[\w-]+&#39;)|[\w-]+|&#39;/gm) || []);
// Array(7) [ &quot;&#39;&quot;, &quot;one&quot;, &quot; &quot;, &quot;&#39;two&#39;&quot;, &quot; &quot;, &quot;three&quot;, &quot;&#39;&quot; ]

Also I've changed it to match only word symbols and minuses (by analogy with next pattern), to exclude matching of &#39;one &#39;.

If matching of phrases in quotes (like &#39;abc abc&#39;) is expected you could you could use \s|(&#39;(?=[\S])[^&#39;]+?(?&lt;=[\S])&#39;)|[\w-]+|&#39;

EDIT: according to corrected input by OP, to allow words containing &#39;, like that&#39;s:

\s|((?&lt;=[\s|^])&#39;[\w-][\w&#39;-]*[\w-]&#39;(?=\s|$))|[\w-][\w&#39;-]*[\w-]|&#39;|\w

huangapple
  • 本文由 发表于 2023年4月6日 23:41:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951361.html
匿名

发表评论

匿名网友

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

确定