-1

Within a foreach loop I am capturing a piece of text of the element if it is displayed. However I only want to grab the number within the element text (both positive and negative).

Currently the text can read either:

+156 on same day
or
-88 on same day

I want to only grab the values from this text so this should either be:

156
or
-88

How can I grab only the numbers and if minus number the negative symbol from the alternativeAirportPrice.Text?

public string GetAlternativeAirportPrice(By airportPriceLocator)
{
    var alternativeAirportPrices = _driver.FindElements(airportPriceLocator);

    foreach (var alternativeAirportPrice in alternativeAirportPrices)
    {
        if (alternativeAirportPrice.Displayed)
            return alternativeAirportPrice.Text;
    }
    return null;
}
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
BruceyBandit
  • 3,978
  • 19
  • 72
  • 144
  • there are numerous ways to do this.. but you could use some of the built in extension methods such as `Char.IsNumeric` do a quick google search for examples online – MethodMan Nov 10 '17 at 21:29
  • This isn't so much a selenium question as much as it is a string parsing question. Searching for that might help in your research. – mrfreester Nov 10 '17 at 21:34
  • 1
    Possible duplicate of [Regex for numbers only](https://stackoverflow.com/questions/273141/regex-for-numbers-only) – cwharris Nov 10 '17 at 22:09
  • Ues regluar expression can make your code look simple. Try ([+-]\d+) in your code, I'm not C# fans, But i try it on browser console, like ('+156 on same day').match(/([+-]\d+)/)[1] , browser console use JavaScript – yong Nov 11 '17 at 00:27

2 Answers2

0

Try that code:

string test = "-123";
string result;
foreach(Char i in test) {
    if (Char.IsNumber(i)) {
        result += i;
    }
}
int value = int.Parse(result);
madoxdev
  • 3,770
  • 1
  • 24
  • 39
0

if you need number as int instead of your line:

return alternativeAirportPrice.Text;

you can write:

    int r;
    int.TryParse(alternativeAirportPrice.Text.Trim().Split(' ').First(), out r);
    return r;

It will work for both cases you've written. If there could be empty string, you can check for empty string before calling string methods. If you might have decimal number - just change int to double. But of cause you gotta change your method return type to int.

SerhiiBond
  • 247
  • 3
  • 8