Would someone write a regular expression for me in .NET?
I recently asked for help with a regular expression; I now know I did开发者_高级运维 not ask for enough!
Can somebody please compose for me a regular expression that will extract all numbers from a string. There could be a single instance of a number, there could be multiple instances of numbers, there will be other text in the string and each of the numbers may or may not contain decimal points. Where decimal points are present, there is no fixed precision. Numbers may also contain thousand seperators (normally a comma).
Examples:
- "(123 items with 234 sub items)" - results: "123", "234"
- "123 @ 234.56%" - results: "123", "234.56"
- "(123 @ 234.56%)" - result: "123", "234.56"
- "@ 123.45 %" - result: "123.45"
- "123 @ 4.56 p" - results: "123", "4.56"
- "12,345.67 and 2345.67" - results: - "12,345.67", "2345.67"
I will be using the .NET regular expression engine.
"[0-9][0-9,.]*"
Perhaps not the most efficient but this matches all of the cases you specified:
[0-9]([0-9]|[,]|)*([\.][0-9]+|)
- [0-9] Ensures a single number is matched
- ([0-9]|[,]|)* Ensures that if there are any more numbers/commas after the first number, they are matched
- ([.][0-9]+|) Ensures that if a decimal point exists, its is matched (will not match if no numbers are specified after the decimal)
Try this [-+]?\b\d+(?:,\d{3})*\.?\d*\b
This thing should ensure that you only get a comma every three numbers.
\d+(?:,\d{3})*(?:\.\d+)?
(0?|[1-9][0-9]?[0-9]?((,[0-9][0-9][0-9])*|[0-9]*))(\.[0-9]+)?
Matches:
0.1234
1,234,567.23
1234567
234.0
.23
Will not match:
0.234,342
1234,2345
1,234,5678
123.
01234
精彩评论