-
Notifications
You must be signed in to change notification settings - Fork 393
Regex parsing #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Regex parsing #64
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
fe6a8ea
Switched parsing from splitting on space to capturing quantity and un…
maherkassim 8592d2e
Updated Regex to allow custom group and decimal separators from Forma…
maherkassim 5413159
Switched parsing to use Trim(), exponential regex to just match digit…
maherkassim bdb087b
GeneratedCode for parsing corrections
maherkassim 718df8c
Separated out unit parsing and added unit parsing tests, Updated defa…
maherkassim 7842466
GeneratedCode for Unit Parsing and Culture Info changes
maherkassim 369e4c3
Switched to using string.Format instead of concatenation via "+"
maherkassim 3b5fd71
GeneratedCode for Switch to using string.Format
maherkassim 7b0a1f0
Updated regex format strings
maherkassim 6662d95
GeneratedCode for updated regex format strings
maherkassim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,6 +21,7 @@ | |
|
||
using System; | ||
using System.Globalization; | ||
using System.Text.RegularExpressions; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Generated code should be a separate commit. |
||
using System.Linq; | ||
using JetBrains.Annotations; | ||
using UnitsNet.Units; | ||
|
@@ -245,29 +246,38 @@ public double As(AccelerationUnit unit) | |
public static Acceleration Parse(string str, IFormatProvider formatProvider = null) | ||
{ | ||
if (str == null) throw new ArgumentNullException("str"); | ||
string[] words = str.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries); | ||
if (words.Length < 2) | ||
|
||
var numFormat = formatProvider != null ? | ||
(NumberFormatInfo) formatProvider.GetFormat(typeof (NumberFormatInfo)) : | ||
NumberFormatInfo.CurrentInfo; | ||
|
||
var numRegex = string.Format(@"[\d., {0}{1}]*\d", // allows digits, dots, commas, and spaces in the quantity (must end in digit) | ||
numFormat.NumberGroupSeparator, // adds provided (or current) culture's group separator | ||
numFormat.NumberDecimalSeparator); // adds provided (or current) culture's decimal separator | ||
var regexString = string.Format("(?<value>[-+]?{0}{1}{2}{3}", | ||
numRegex, // capture base (integral) Quantity value | ||
@"(?:[eE][-+]?\d+)?)", // capture exponential (if any), end of Quantity capturing | ||
@"\s?", // ignore whitespace (allows both "1kg", "1 kg") | ||
@"(?<unit>\S+)"); // capture Unit (non-whitespace) input | ||
|
||
var regex = new Regex(regexString); | ||
GroupCollection groups = regex.Match(str.Trim()).Groups; | ||
|
||
var valueString = groups["value"].Value; | ||
var unitString = groups["unit"].Value; | ||
|
||
if (valueString == "" || unitString == "") | ||
{ | ||
var ex = new ArgumentException( | ||
"Expected two or more words. Input string needs to be in the format \"<quantity> <unit>\".", "str"); | ||
"Expected valid quantity and unit. Input string needs to be in the format \"<quantity><unit> or <quantity> <unit>\".", "str"); | ||
ex.Data["input"] = str; | ||
ex.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString(); | ||
throw ex; | ||
} | ||
|
||
try | ||
{ | ||
// Unit string is the last word, since units added so far don't contain spaces. | ||
// Value string is everything else since number formatting can contain spaces. | ||
string[] allWordsButLast = words.Take(words.Length - 1).ToArray(); | ||
string lastWord = words[words.Length - 1]; | ||
|
||
string unitString = lastWord; | ||
string valueString = string.Join(" ", allWordsButLast); | ||
|
||
var unitSystem = UnitSystem.GetCached(formatProvider); | ||
|
||
AccelerationUnit unit = unitSystem.Parse<AccelerationUnit>(unitString); | ||
AccelerationUnit unit = ParseUnit(unitString, formatProvider); | ||
double value = double.Parse(valueString, formatProvider); | ||
|
||
return From(value, unit); | ||
|
@@ -281,6 +291,32 @@ public static Acceleration Parse(string str, IFormatProvider formatProvider = nu | |
} | ||
} | ||
|
||
/// <summary> | ||
/// Parse a unit string. | ||
/// </summary> | ||
/// <example> | ||
/// Length.ParseUnit("m", new CultureInfo("en-US")); | ||
/// </example> | ||
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> | ||
/// <exception cref="UnitsNetException">Error parsing string.</exception> | ||
public static AccelerationUnit ParseUnit(string str, IFormatProvider formatProvider = null) | ||
{ | ||
if (str == null) throw new ArgumentNullException("str"); | ||
var unitSystem = UnitSystem.GetCached(formatProvider); | ||
|
||
var unit = unitSystem.Parse<AccelerationUnit>(str.Trim()); | ||
|
||
if (unit == AccelerationUnit.Undefined) | ||
{ | ||
var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AccelerationUnit."); | ||
newEx.Data["input"] = str; | ||
newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString(); | ||
throw newEx; | ||
} | ||
|
||
return unit; | ||
} | ||
|
||
#endregion | ||
|
||
/// <summary> | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we should consider caching this regex as a static field and construct it with the Compile flag for performance.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will this be affected by a change to the given formatProvider?
For example, running tests with different cultures.