473,703 Members | 2,341 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert.ToStrin g( double ) + xsd:pattern + RegEx == ?

expanding this message to microsoft.publi c.dotnet.xml

Greetings

Please direct me to the right group if this is an inappropriate place
to post this question. Thanks.

I want to format a numeric value according to an arbitrary regular
expression.

Background:

I have an XML schema that I have no control over. It is filled with
simpleTypes with restrictions that include xsd:pattern elements, eg:

<xsd:restrictio n base="xsd:float ">
<xsd:minInclusi ve value="0.000" />
<xsd:maxInclusi ve value="10.000" />
<xsd:pattern value="\d{1,2}\ .\d{3}" />
</xsd:restriction >

These patterns and BaseTypes vary widely.

I am dynamically creating an XmlDocument at runtime and validating it
against the schema. Each XmlDocumentElem ent.InnerText property is
populated from a data structure that contains an object reference that
points to a value of the appropriate type. That is: The object
references may point to a float or to a string or whatever is called
for, depending on the BaseType of the corresponding simpleType.
(Usings strings for everything is not an option.)

The problem is that in order to create the XmlDocument, I have to
convert an object that might actually be a float or an int in to a
formatted string.

I can't just go

myElement.Inner Text = Convert.ToStrin g( Convert.ToDoubl e( myObject ) );

because myElement.Inner Text will then contain strings that look like
this

1.000 ==> "1"
1.050 ==> "1.05"

which cannot be guaranteed to satisfy the schema. It certainly doesn't
satisfy the one above. In the case of that schema, I would obviously
want to have conversions like this:

1.000 ==> "1.000"
1.050 ==> "1.050"

Yes, I know I can easily write code to do this for a single regular
expression, but the problem is that there is no guarantee what the
xsd:pattern is going to be. Hard coding something that uses three
decimal places just won't do.

Here's what I would like to do:

myElement.Inner Text = FormatAccording ToRegEx( Convert.ToDoubl e(
myObject ), myXsdPattern );

Remember, myXsdPattern could be anything, so I can't do something like

Regex.Replace( Convert.ToStrin g( Convert.ToDoubl e( myObject ) ),
myXsdPattern, "${1},${2}.${3} " ); // not sure about syntax here

That won't work if myXsdPattern = "\d{1,}.\d{ 3}" or "\d{1,}.\d{ 1}" or
"-{0,1}\d{1,2}.\d {1}" (to list a few examples); and even if it did, I
think I would need to have access to the schema so I could interject
parentheses in to the regular expressions/xsd:patterns. As I said, I
have no control over the schema. (Although, the ultimate solution may
indeed require me to read the xsd:pattern in, insert parentheses
according to some algorithm and then do something like the code
fragment above. I don't know.)

Now, I'm pretty sure that xsd:pattern will only be used with numeric
values like xsd:float and xsd:int in the schema. I don't think it
would be possible to do this with an arbitrary string anyway because in
many cases, several formatted outputs are possible from one input... so
I would think this simplifies the problem a bit. (Several outputs are
possible from one input with numbers as well, but they all mean the
same thing -- leading zeros and commas are pretty irrelevant. A number
is still a number.)

I hope I'm being clear. I'm grammatically challenged today.

I know this is a bit backward, but I'm though I'd check and see if
anyone has already written code to do this. I will be grateful for any
and all suggestions -- even guesses about what to try.
Thanks in advance.

Tony

Nov 12 '05 #1
4 9756
ae********@yaho o.com wrote in
news:11******** **************@ z14g2000cwz.goo glegroups.com:
expanding this message to microsoft.publi c.dotnet.xml

Greetings

Please direct me to the right group if this is an inappropriate
place to post this question. Thanks.

I want to format a numeric value according to an arbitrary
regular expression.

Background:

I have an XML schema that I have no control over. It is filled
with simpleTypes with restrictions that include xsd:pattern
elements, eg:

<xsd:restricti on base="xsd:float ">
<xsd:minInclus ive value="0.000" />
<xsd:maxInclus ive value="10.000" />
<xsd:pattern value="\d{1,2}\ .\d{3}" />
</xsd:restriction >

These patterns and BaseTypes vary widely.

I am dynamically creating an XmlDocument at runtime and
validating it against the schema. Each
XmlDocumentElem ent.InnerText property is populated from a data
structure that contains an object reference that points to a
value of the appropriate type. That is: The object references
may point to a float or to a string or whatever is called for,
depending on the BaseType of the corresponding simpleType.
(Usings strings for everything is not an option.)

The problem is that in order to create the XmlDocument, I have
to convert an object that might actually be a float or an int in
to a formatted string.

I can't just go

myElement.Inner Text = Convert.ToStrin g( Convert.ToDoubl e(
myObject ) );

because myElement.Inner Text will then contain strings that look
like this

1.000 ==> "1"
1.050 ==> "1.05"

which cannot be guaranteed to satisfy the schema. It certainly
doesn't satisfy the one above. In the case of that schema, I
would obviously want to have conversions like this:

1.000 ==> "1.000"
1.050 ==> "1.050"

Yes, I know I can easily write code to do this for a single
regular expression, but the problem is that there is no
guarantee what the xsd:pattern is going to be. Hard coding
something that uses three decimal places just won't do.

Here's what I would like to do:

myElement.Inner Text = FormatAccording ToRegEx( Convert.ToDoubl e(
myObject ), myXsdPattern );

Remember, myXsdPattern could be anything, so I can't do
something like

Regex.Replace( Convert.ToStrin g( Convert.ToDoubl e( myObject ) ),
myXsdPattern, "${1},${2}.${3} " ); // not sure about syntax here

That won't work if myXsdPattern = "\d{1,}.\d{ 3}" or
"\d{1,}.\d{ 1}" or "-{0,1}\d{1,2}.\d {1}" (to list a few
examples); and even if it did, I think I would need to have
access to the schema so I could interject parentheses in to the
regular expressions/xsd:patterns. As I said, I have no control
over the schema. (Although, the ultimate solution may indeed
require me to read the xsd:pattern in, insert parentheses
according to some algorithm and then do something like the code
fragment above. I don't know.)

Now, I'm pretty sure that xsd:pattern will only be used with
numeric values like xsd:float and xsd:int in the schema. I don't
think it would be possible to do this with an arbitrary string
anyway because in many cases, several formatted outputs are
possible from one input... so I would think this simplifies the
problem a bit. (Several outputs are possible from one input with
numbers as well, but they all mean the same thing -- leading
zeros and commas are pretty irrelevant. A number is still a
number.)

I hope I'm being clear. I'm grammatically challenged today.

I know this is a bit backward, but I'm though I'd check and see
if anyone has already written code to do this. I will be
grateful for any and all suggestions -- even guesses about what
to try. Thanks in advance.


Tony,

Interesting problem. Regexes are usually used to see if a given piece of
data matches a given format. I'm not aware of any way to directly use a
regex to *make* the data match the format.

FWIW, .Net has numeric format strings that supply this functionality.

http://msdn.microsoft.com/library/de...matstrings.asp

or

http://tinyurl.com/4tus6

I know you stated you have no direct control over the XSD, but if it's
feasible, you should find a way to get the author of the XSD to insert
an additional element in the xsd:restriction element. Something like:

<xsd:format value="0#.###"/>

If that's not possible, there may be a way to hack something together...

Correct me if I'm wrong, but it seems the algorithm you're trying to
produce is:

int input = 4;
string regex = "\d{1,2}\.\d{3} "; // No optional clauses.
string result = BlackBox(input, regex);

// result would be 4.000.

int input = -4;
string regex = "-{0,1}\d{1,2}.\d {1}"; // Optional minus sign.
string result = BlackBox(input, regex);

// result would be -4.0.

I'm assuming that illegal input values that are out of range of the
supplied regular expression will be caught using xsd:minInclusiv e
and xsd:maxInclusiv e.

I'm also assuming the format of the regex roughly matches the format
of the xsd:minInclusiv e and xsd:maxInclusiv e values. If that's the
case, then you may be able to use that knowledge to use the supplied
regex to format the input value.

It appears from the regex examples you give that the number of digits
to the right side of the decimal point are usually fixed, whereas the
number of digits on the left side of the decimal point are variable.

Using that observation, it's possible to pad the input value with
zeros on the right side of the decimal point, and use the regex to
extract the formatted number:
// Compile with "csc /t:exe example.cs"

using System;
using System.Text.Reg ularExpressions ;

namespace Example
{
public class TestClass
{
public static int Main(string[] args)
{
Console.WriteLi ne(BlackBox("4" , @"\d{1,2}\.\d{3 }", "10.000"));
Console.WriteLi ne(BlackBox("4" , @"\d{1,}.\d{3}" , "1000.000") );
Console.WriteLi ne(BlackBox("4" , @"\d{1,}.\d{1}" , "1000.0"));
Console.WriteLi ne(BlackBox("-4", @"-{0,1}\d{1,2}.\d {3}", "10.000"));

return 0;
}

public static string BlackBox(string input, string regex, string maxInput)
{
const string decimalPoint = ".";

if (maxInput.Index Of(decimalPoint ) > 0)
{
if (input.IndexOf( decimalPoint) < 0)
input += decimalPoint;

// Pad input with zeros to the right of the decimal
// point so it matches the number of decimal places in
// maxInput (we don't care about numbers on the left side of
// the decimal point).
// For example, if maxInput = 12.3456, and
// input = 9.8, pad input so it equals 9.8000.

input += new string('0',
GetNumberOfDeci malPlaces(maxIn put) -
GetNumberOfDeci malPlaces(input ));
}

return Regex.Match(inp ut, regex).Groups[0].ToString();
}

public static int GetNumberOfDeci malPlaces(strin g input)
{
return Regex.Match(inp ut, @"\.(?<digits>\ d*)",
RegexOptions.Ex plicitCapture). Groups["digits"].ToString().Len gth;
}
}
}

--
Hope this helps.

Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/
Nov 12 '05 #2
Thanks for the reply Chris. Your solution certainly covers a wide
range of possibilities. I think relying on something like maxInclusive
is about as good as it's going to get. I'll throw an exception if they
don't have a [min|max][Inclusive|Exclu sive] restriction allong with the
pattern.

One more question, though... Wouldn't this

e.InnerText =
Convert.ToDoubl e(objectValue). ToString("F"+(m axExclusiveValu e.Length-m_maxExclusiveV alue.IndexOf('. ')-1).ToString());

do the same thing? If not, what are the disadvantages of doing it this
way?

Thanks
Tony

Nov 12 '05 #3
ae********@yaho o.com wrote in
news:11******** **************@ z14g2000cwz.goo glegroups.com:
Thanks for the reply Chris. Your solution certainly covers a
wide range of possibilities. I think relying on something like
maxInclusive is about as good as it's going to get. I'll throw
an exception if they don't have a [min|max][Inclusive|Exclu sive]
restriction allong with the pattern.

One more question, though... Wouldn't this

e.InnerText =
Convert.ToDoubl e(objectValue). ToString("F"+(m axExclusiveValu e.Len
gth-m_maxExclusiveV alue.IndexOf('. ')-1).ToString());

do the same thing? If not, what are the disadvantages of doing
it this way?


Tony,

If both solutions work for your data, then apply Occam's Razor. I
was probably too focused on the regular expression, and honestly
didn't think of using the maxInclusive value to build a format
string.

Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/
Nov 12 '05 #4
It appears that both solutions do indeed work. I just wanted to be
sure that you didn't use a regular expression for a particular reason.
I see you are now indicating that you didn't.

In looking at the schema, I see that sometimes maxInclusive isn't in
the format specified by the pattern! However, the DefaultValue for the
element always is, so I decided to go with that. So...

m_element.Inner Text = Convert.ToDoubl e( objectValue
).ToString("F"+ (m_schemaElemen t.DefaultValue. Length-m_schemaElement .DefaultValue.I ndexOf('.')-1).ToString());
Thanks again.
Tony

Nov 12 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
32070
by: Phd | last post by:
Hi, I'm writing a regex related program that lets the user supplies the regex definition. Is there an easy way to convert a string into a raw string? Cheers
17
12833
by: Suzanne Vogel | last post by:
I'd like to convert a double to a binary representation. I can use the "&" bit operation with a bit mask to convert *non* float types to binary representations, but I can't use "&" on doubles. To get around this limitation on double, I'd like to keep the bits of the double the *same* but change its interpretation to long. I can use "&" on longs. I tried to use reinterpret_cast for this purpose, but it returned zero every time. double...
8
2984
by: Johnny | last post by:
I need to determine whether a text box contains a value that does not convert to a decimal. If the value does not convert to a decimal, I want to throw a MessageBox to have the user correct the value in the text box. I have the following code but when the user enters a decimal value the Regex.IsMatch catches it (ex. 250.50 should be allowed, but 250.50.0 should not). My code is as follows: if( ! Regex.IsMatch( tboxQtyCounted.Text,...
4
3478
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a numeric value according to an arbitrary regular expression.
16
5874
by: Charles Law | last post by:
I have a string similar to the following: " MyString 40 "Hello world" all " It contains white space that may be spaces or tabs, or a combination, and I want to produce an array with the following elements arr(0) = "MyString" arr(1) = 40 arr(2) = "Hello world"
10
8969
by: ksrajalakshmi | last post by:
Hai , in a textbox am having text as "(20/100)+pay1*pay2" .it's a formula. and stored in a particular variable. string strformula="(20/100)+pay1*pay2" ; i've to substitute the value of the variable 'pay1' & 'pay2' and finding the value of that strformula. can any onr tell me how to find 'pay1' and 'pay2' in the variable
34
11193
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code snippet that I wrote today that gives me an instant implementation of the pattern. I could easily just always use such an implementation instead of a standard enum, so I wanted to know what you experts all thought. Is there a case for standard enums?
5
23467
by: SMichal | last post by:
Hi, how can I parse string "? 20.000" to double ?
3
2195
by: =?Utf-8?B?TWFya19C?= | last post by:
The following is working for me but I want to include numbers in scientific notation. public double Evaluate( string expr ) { const string Num = @"(\-?\d+\.?\d*|\-?\.\d+)" Regex reMulDiv = new Regex(Num + @"\s*()\s*" + Num); other stuff:
0
8759
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8669
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9251
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3125
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2453
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.