1

Like many others, I'm crap at regex and particularly bad when it comes to regex in javascript.

I have a string that can take two formats:

var str = "This is a string t:1h"

or

var str = "This is a string t:1h,2h,3h"

I would like to match the 't:X' part or 't:X,X,X' part (whichever it happens to be) from the string and handle that separately.

Can anybody clever show me how to do a regex match on this string for this?

I haven't gotten very far. I have:

var reg = /\s?/m;
parsed = str.match(reg);

Please help.

5
  • 1
    You're missing the / at the beginning of the regexp. Commented Nov 7, 2013 at 23:16
  • In fact, it looks like almost all of your regexp is missing. Did you mess up copying into the question? Commented Nov 7, 2013 at 23:17
  • 1
    "Like many others, I'm crap at regex and particularly bad when it comes to regex in javascript" -- Regex are pretty universal, once you learn them you can use them pretty much in any language with minor variations. I'm sure many people including myself have learned here regular-expressions.info. Commented Nov 7, 2013 at 23:18
  • Nope, I just haven't a clue what to put there :) Sorry about that. I'm learning as you comment. Commented Nov 7, 2013 at 23:19
  • Learning regex is an important exercise, and it's good that you're doing that. But in this case, it's more power than you need. You can get by adequately simply with str.substring(str.lastIndexOf("t:")). Commented Nov 7, 2013 at 23:21

2 Answers 2

2

You mean like this?

var test = "This is a string t:1h,2h,3h"
var matches = test.match(/t:.*/)
console.debug(matches[0])

Gives

t:1h,2h,3h
Sign up to request clarification or add additional context in comments.

2 Comments

Yep! That's what I wanted. Thanks!
If you want more strict validation, use: var matches = test.match(/t:(\dh,?)*/)
2

This should do the trick:

var str = "This is t:1h,2h,3h bla bla";
var reg = new RegExp("t:[0-9]h(,[0-9]h)*");
var parsed = str.match(reg)[0];

One could also use the "special-RegExp-writing" of Javascript:

var parsed = str.match(/t:[0-9]h(,[0-9]h)*/)[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.