dolphone bubleine
dolphone bubleine

Reputation: 691

What is the regular expression to match all text after a certain character?

I know this question has been asked many times but those examples aren't working for me.

I'm trying to get the minute part of time in a single regular expression. What I have is:

minute = new RegExp(":[0-9]{1,2}").exec(time).toString().replace(":", "");

How can I get this done without using the .replace?

Upvotes: 0

Views: 134

Answers (6)

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

try this:

minute = new RegExp(":([0-9]{1,2})").exec(time)[1];

This will match the whole thing, but store whatever the part in parenthesis matches for you to use later. Hence the [1].



Going to leave the following in here, in case somebody comes looking for a non-javascript answer.

This will not work in javascript, as it does not support lookbehinds. Thanks @999.

Try using a positive lookbehind. That way you won't even need to replace :)

minute = new RegExp("(?<=:)[0:9]{1,2}").exec(time).toString();

[0:9]{1,2} is the pattern you actually want to match. (?<=:) just makes sure it has a colon behind it, without actually consuming anything.

Upvotes: 0

Chris Baker
Chris Baker

Reputation: 50592

Assuming that time is a time string like "10:15 AM", you can (and should) use the Date object. This is the right tool for the job, it is more flexible because it is made to deal with date/time data.

var time = '10:15 AM';
// handle either a full date string OR a time string
var d = new Date(time);
if (isNaN(d.getTime()))
    var d = new Date('1/1/2012 '+time);

Try it: http://jsfiddle.net/gsg8X/

Probably better than trying to determine if the seconds are there or not, which could break a regular expression, or make it more complicated than it needs to be. I think you're better off using a date/time related tool to parse date/time related data.

Documentation

Upvotes: 1

Logical Fallacy
Logical Fallacy

Reputation: 3107

Store "time" as a Date object, if you aren't already doing that. Then you can use getMinutes() to pull the minutes component out.

minute = time.getMinutes();

Upvotes: 1

greihund
greihund

Reputation: 192

You need some kind of position anchor to grab the last part of the string

(/:([0-9]{1,2}$)/)

Upvotes: 0

James
James

Reputation: 111880

Assuming time is of the format NN:NN then the minutes can be extracted like so:

minute = time.match(/\d{2}$/)[0];

Or a simple split:

minute = time.split(':')[1];

Upvotes: 4

Matt Ball
Matt Ball

Reputation: 359776

Use a capture group to get only what you want.

var time = '12:29',
    minute = /:([0-9]{1,2})/.exec(time)[1];

// minute is "29"

Upvotes: 2

Related Questions