Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript (node) regex doesn't seem to match start of string

Javascript (node) regex doesn't seem to match start of string

Problem

im struggling with regular expressions in Javascript, they don't seem to start at the beginning of the String. In a simple example bellow I want to get the file name and then everything after the first colon

 //string
 file.text:16:  lots of random text here with goes on for ages

 //regex
 (.?)[:](.*)

 // group 1 returns 't'
Problem courtesy of: henry.oswald

Solution

Try this regex:

/^([^:]+)[:](.*)/

Explaination:

^       #Start of string
(       #Start of capturing class #1
  [^:]    #Any character other than :
  +       #One or more of the previous character class
)       #End of capturing class #1
[:]     #One :
(.*)    #Any number of characters other than newline

The ? operator captures zero or one of the previous symbol only.

You could also use string operations instead:

str = "file.text:16:";
var n = str.indexOf(":");
var fileName = str.substr(0, n);
var everythingElse = str.substr(n);
Solution courtesy of: Digital Plane

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Javascript (node) regex doesn't seem to match start of string

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×