简体   繁体   中英

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.

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/.exec('i\\'m in') it evaluates to ["m in"]

i also tried /i\\'m in/ which doesn't work in my code and when but when i run:

/i\\'m in/.exec('i\\'m in') it evaluates to ["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.

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

Regex --> [i\\'m] in

It will match 4 characters. The first character can be either i or \\' or m . The second character is a space and third character is i and fourth character is n . You don't have to use \\ for ' in regex. But you will need to use \\ for ' in JS string.

String --> 'i\\'m in'
m in is the string the regex matches. It can also match these strings: i in , ' in

If you want to match all 6 characters of string you can use something like this:

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

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

And if you want to match either in or out, you can use an or operator.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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