0

I am trying to get the number (123) from data written in the format 123:AB.CD.EF.GH.IJ using Javascript.

Currently I have a regular expression /^[0-9]*(?=\:)/ and using

var ABC = pattern.match(regex);

but I keep coming up empty handed. What is wrong with my expression?

4
  • 3
    What are pattern and regex? Because "123:AB.CD.EF.GH.IJ".match(/^[0-9]*(?=\:)/) works. Commented Apr 4, 2011 at 17:20
  • '123:AB.CD.EF.GH.IJ'.match(/^[0-9]*(?=\:)/) works just fine for me. Your problem must be elsewhere. Commented Apr 4, 2011 at 17:22
  • Sorry was very vague, pattern is just the text in the format I gave and regex is that regular expression defined using var regex = RegExp("^[0-9]*(?=\:)", "") Commented Apr 4, 2011 at 17:22
  • Try changing the ^ to a \b and see if that helps. Commented Apr 4, 2011 at 17:45

3 Answers 3

6

Or you could skip regex and use pattern.split(':')[0].

Sign up to request clarification or add additional context in comments.

4 Comments

I like this even better. It's good to avoid regexes if not doing complicated text processing.
Thanks and good answer. I really didnt want to pass another variable. Cheers out to everybody.
Nice. Sometimes simpler is better.
Thanks! I just really never get regexes, which makes me good at thinking of ways to avoid them...
0

Try

var number = value.replace(/:.*/);   // where value is the "123:AB.CD.EF.GH.IH" string

Sometimes doing the same thing a different way will yeidl better result, I've found with regexs.

Comments

0

Match returns an array. You might need pattern.match(regex)[1] where 1 is the matched string. You don't need the (?=\:) at the end. You will also need to specify what you are capturing.

Try this:

regex = /^([0-9]*)/

The parenthesis say what you want to match. Remember, match returns an array. Use JSON.stringify() to find what you're getting. JSON.stringify(ABC). JSON is supported on FF, Chrome, and Safari I believe.

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.