简体   繁体   English

使用正则表达式将确切的字符串与撇号进行匹配

[英]Regular expression to match exact string with apostrophe

i'm trying to write regular expressions to match these exact strings: 我正在尝试编写正则表达式以匹配这些确切的字符串:

  • "i'm in" “算我一个”
  • "i'm out" “我出去了”

i'm not searching for a single character. 我不是在寻找一个字符。 i'm searching for an exact string and trying to understand how reg exs work. 我正在寻找一个确切的字符串,并试图了解正则表达式如何工作。

i've read the MDN docs and the chapter in Eloquent JS, as well as searched on stack overflow conversations. 我已经阅读了MDN文档和Eloquent JS中的章节 ,并在堆栈溢出对话中进行了搜索。

i understand that anything in square brackets represents a character set and the characters do not have to occur in a sequence. 我知道方括号中的任何内容都代表一个字符集,并且这些字符不必按顺序出现。

i tried /[i\\'m] in/ which works in my code but when i run: 我试过/[i\\'m] in/在我的代码中有效,但是当我运行时:

/[i\\'m] in/.exec('i\\'m in') it evaluates to ["m in"] /[i\\'m] in/.exec('i\\'m in')计算结果为[“ m in”]

i also tried /i\\'m in/ which doesn't work in my code and when but when i run: 我也尝试过/i\\'m in/在我的代码中不起作用以及何时但当我运行时:

/i\\'m in/.exec('i\\'m in') it evaluates to ["i'm in"] /i\\'m in/.exec('i\\'m in')评估为[“ i'm in”]

not sure why this is so. 不知道为什么会这样。 any pointers or illuminations would be great. 任何指针或照明都很好。

Your regex matches only 4 characters while your complete string is 6 characters long. 您的正则表达式仅匹配4个字符,而完整字符串的长度为6个字符。

/[i\'m] in/.exec('i\'m in')

Regex --> [i\\'m] in 正则表达式-> [i\\'m] in

It will match 4 characters. 它将匹配4个字符。 The first character can be either i or \\' or m . 第一个字符可以是i\\'m The second character is a space and third character is i and fourth character is n . 第二个字符是space ,第三个字符是i ,第四个字符是n You don't have to use \\ for ' in regex. 您不必在正则表达式中将\\用作' But you will need to use \\ for ' in JS string. 但是,你将需要使用\\'在JS字符串。

String --> 'i\\'m in' 字符串-> 'i\\'m in'
m in is the string the regex matches. m in是正则表达式匹配的字符串。 It can also match these strings: i in , ' in 它还可以匹配以下字符串: i in' in

If you want to match all 6 characters of string you can use something like this: 如果要匹配字符串的所有6个字符,则可以使用如下所示的内容:

/i'm in/.exec('i\'m in')

Demo: https://repl.it/EfDS/3 演示: https//repl.it/EfDS/3

And if you want to match either in or out, you can use an or operator. 而且,如果您要进行匹配,请使用or运算符。

/i'm (in|out)/.exec('i\'m out')

Demo: https://repl.it/EfDS/4 演示: https : //repl.it/EfDS/4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM