Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex for colon?

I'm wondering how I can use javascript regex to match a word like:

Name:

with all variations of spaces ? This is where I'm getting stuck. i.e.

  • Name<space>: Fred
  • Name:<space>Fred or Name<space>:<space>Fred

Note the positioning of the spaces after the name, after the colon etc ?

I was hoping something like /(name(\s*:\s*)?)\w/g would work but it doesn't :(

like image 812
Andy Avatar asked Jun 05 '12 06:06

Andy


People also ask

How do you write a colon in RegEx?

In character class [-+_~. \d\w] : - means - + means +

How do you match a semicolon in RegEx?

Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions. As a workaround, use the regular expression standard of ASCII.

What does question mark colon mean in RegEx?

The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value.

What is the use of * in regular expression?

*. * , returns strings beginning with any combination and any amount of characters (the first asterisk), and can end with any combination and any amount of characters (the last asterisk). This selects every single string available.


1 Answers

  • Name starts with a capital letter. The regex should also match name starting with a capital N.

    • If you want the entire regex to be case insensitive, add the i flag at the end.
    • If you only want name to start with a lower or upper case N, then use a set
  • The * means 0 or more. The ? is not needed anymore.

Something like this should work

/Name\s*:\s*\w*/g    //matches "Name"

/[Nn]ame\s*:\s*\w*/g //matches "Name" or "name"

/name\s*:\s*\w*/gi   //the entire regex is case insensitive
like image 84
Joseph Avatar answered Oct 13 '22 09:10

Joseph