• 0

RegEx newbie


Question

Having never really used Regex before and probably need to, I went to http://regexone.com/ to get the basics.

 

I did the basic tutorials and have moved onto the first practical example. I got this working but my solution differs from their answer. Can anyone explain why?

Below are a few different formats of numbers that you might encounter. Notice how you will have to match the decimal point itself and not an arbitrary character using the dot metacharacter. If you are having trouble skipping the last number, notice how that number ends the line compared to the rest.

match text: 3.14529

match text: -255.34

match text: 128

match text: 1.9e10

match text: 123,340.00

skip text: 720p

My solution: -?\d+(,\d+)?\.?(\d+e?\d+)$

Their solution: ^-?\d+(,\d+)*(\.\d+(e\d+)?)?$

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Your solution would not match a number with multiple comma separators. E.g. 123,456,789 as you use a ? instead of a * after (,\d+)?

Your solution would match 100e6 where there's would only match 100.0e6

You would not be able to match 100.0 as you require 2 numbers after the decimal point.

 

There are probably quite a few other differences. It might be worth testing with a wider range of inputs to see what these two regexes miss.

http://www.regexper.com/ is a useful size that visualises regexes

  • Like 1
Link to comment
Share on other sites

  • 0

Added to Lant's reply, ^ and $ limits the start and end of the matched text respectively.

Your regex would match without taking into account if the match is in the middle of a string.

^ start matching from the beginning of the string

$ end matching at the ending of the string

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.