简体   繁体   中英

Regex to match a number with decimals

I have the following regex:

var matches = Regex.Matches(s, @"ratingValue"" content=""(?<content>(?:(.|\n)(?!""></span>))+)");

However, it gives the output with "number.", anything after the . is not taken. For example, if the number is 4.0 it will output 4. or if it's 3.5 it gives 3. .

How can I get the decimals as well?

Example input:

<span itemprop="ratingValue" content="4.0"></span>

I need to output 4.0 .

You can use LINQ to XML:

string xml = @"<span itemprop=""ratingValue"" content=""4.0""></span>";

string content = XElement.Parse(xml).Attribute("content").Value;

decimal value = Convert.ToDecimal(content, CultureInfo.InvariantCulture);

I've changed your regex so it returns the decimal number as the match:

var matches = Regex.Matches(s, @"(?:ratingValue"" content="")(?<content>[\r\n\d\.]*)(?:""></span>)");

Is this what you were after? It returns 4.0 from the provided sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM