ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Need help with some string manip in C#

(1/2) > >>

kyrathaba:
Maybe someone can help me with this. I'm needing C# code that reliably does the following: given a string of characters, it returns a substring of characters. If the substring has an improperly formatted decimal number, that is the returned substring. Otherwise it returns a zero-length string.

So, as examples, it would detect the following in string "abc3. 04xta": -> returns "3. 04"

And for this string: "3bcd4 0.  25z10": returns "4 0.  25"

What I'm ultimately wanting is for the code to do a string.replace( ) that fixes the misformatting:

"abc3. 04xtra" becomes "abc3.04xtra", and "3bcd4 0.  25z10" becomes "3bcd40.25z10".

I know regular expressions is probably the way to go, but I'm having trouble getting my head around them.

The method I'd like would either return the poorly formatted "decimal number" substring; or, optionally,
it could fix the formatting in that substring and replace all occurrences in the larger string.

The end result is that it would turn this sentence...

"The bread was $3 .49, and it had always been $2 .15 before."

...into the following...

"The bread was $3.49, and it had always been $2.15 before."

mwb1100:
What constitutes an "an improperly formatted decimal number"?  Is it a decimal number that contains spaces (or whitespace characters)?

What would you want to be returned for the following:

    "abc3.-04xta"

or

    "abc6/. 7?8xta"

kyrathaba:
For my purposes, an improperly formatted decimal number is any substring which, when any interleaved whitespace or other non-decimal, non alphanumeric characters are removed, forms a decimal number.

"abc3.-04xta" becomes "abc3.04xta"

"abc6/. 7?8xta" becomes "abc6.78xta"

Renegade:
Does this case present a problem for you? (It is properly formatted.)

The fleet consists of 10 2,000-TEU vessels.

If it does, I think you are in for a world of hurt in deciding how things get resolved.

Also, this case:

The apples were handed out, and John got 10. 5 of them were rotten.

But, just off the cuff, does this pattern work?

([0-9 ]+)\.([0-9 ]+)

kyrathaba:
That looks workable,  Ren. But any regex would need to capture and replace whitespace before,  among and after the numbers: "9. 07" becomes "9.07", and " 7   6 . 04" becomes "76.04"

Navigation

[0] Message Index

[#] Next page

Go to full version