Ho l'obbligo di trovare ed estrarre un numero contenuto in una stringa.
Ad esempio, da queste stringhe:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
Come posso fare questo?
1.5? Notazione esponenziale come 1.5E45?
Ho l'obbligo di trovare ed estrarre un numero contenuto in una stringa.
Ad esempio, da queste stringhe:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
Come posso fare questo?
1.5? Notazione esponenziale come 1.5E45?
Risposte:
passare attraverso la stringa e utilizzare Char.IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
b == "System.Linq.Enumerable..". Corretto (e ancora più semplice) sarebbeb = String.Join("", a.Where(char.IsDigit))
new string(char[])costruttore.
\d+è la regex per un numero intero. Così
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
restituisce una stringa contenente la prima occorrenza di un numero in subjectString.
Int32.Parse(resultString) ti darà quindi il numero.
Regex.Match(subjectString, @"-?\d+").Valueinvece
Ecco come pulisco i numeri di telefono per ottenere solo le cifre:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
string numericPhone =new String(phone.Where(Char.IsDigit).ToArray());
usa espressione regolare ...
Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");
if (m.Success)
{
Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
Console.WriteLine("You didn't enter a string containing a number!");
}
Regex.Split può estrarre numeri da stringhe. Ottieni tutti i numeri che si trovano in una stringa.
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
Produzione:
Numero: 4 Numero: 40 Numero: 30 Numero: 10
Ecco una Linqversione:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
"123iuow45ss".AsEnumerable().Where(char.IsDigit)?
from t .. select tridondanza, ma comunque, evviva.
Un'altra semplice soluzione che utilizza Regex Dovresti usare questo
using System.Text.RegularExpressions;
e il codice è
string var = "Hello3453232wor705Ld";
string mystr = Regex.Replace(var, @"\d", "");
string mynumber = Regex.Replace(var, @"\D", "");
Console.WriteLine(mystr);
Console.WriteLine(mynumber);
Puoi anche provare questo
string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
Basta usare un RegEx per abbinare la stringa, quindi convertire:
Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
Ecco un altro Linqapproccio che estrae il primo numero da una stringa.
string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
.SkipWhile(x => !char.IsDigit(x))
.TakeWhile(x => char.IsDigit(x))
.ToArray()), out result);
Esempi:
string input = "123 foo 456"; // 123
string input = "foo 456"; // 456
string input = "123 foo"; // 123
Per coloro che desiderano un numero decimale da una stringa con Regex in DUE righe:
decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);
La stessa cosa vale per float , long , ecc ...
string input = "Hello 20, I am 30 and he is 40";
var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
Puoi farlo usando la Stringproprietà come sotto:
return new String(input.Where(Char.IsDigit).ToArray());
che fornisce solo un numero dalla stringa.
La domanda non afferma esplicitamente che vuoi solo i caratteri da 0 a 9, ma non sarebbe difficile credere che sia vero dal tuo esempio e dai tuoi commenti. Quindi ecco il codice che lo fa.
string digitsOnly = String.Empty;
foreach (char c in s)
{
// Do not use IsDigit as it will include more than the characters 0 through to 9
if (c >= '0' && c <= '9') digitsOnly += c;
}
Perché non vuoi usare Char.IsDigit () - I numeri includono caratteri come frazioni, pedici, apici, numeri romani, numeratori di valuta, numeri cerchiati e cifre specifiche dello script.
Metodo di estensione per ottenere tutti i numeri positivi contenuti in una stringa:
public static List<long> Numbers(this string str)
{
var nums = new List<long>();
var start = -1;
for (int i = 0; i < str.Length; i++)
{
if (start < 0 && Char.IsDigit(str[i]))
{
start = i;
}
else if (start >= 0 && !Char.IsDigit(str[i]))
{
nums.Add(long.Parse(str.Substring(start, i - start)));
start = -1;
}
}
if (start >= 0)
nums.Add(long.Parse(str.Substring(start, str.Length - start)));
return nums;
}
Se vuoi anche numeri negativi, modifica semplicemente questo codice per gestire il segno meno ( -)
Dato questo input:
"I was born in 1989, 27 years ago from now (2016)"
L'elenco dei numeri risultanti sarà:
[1989, 27, 2016]
se il numero ha un punto decimale, puoi usare di seguito
using System;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(Regex.Match("anything 876.8 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("anything 876 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876435", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876.435", @"\d+\.*\d*").Value);
}
}
}
risultati:
"nulla 876,8 nulla" ==> 876,8
"nulla 876 niente" ==> 876
"$ 876435" ==> 876435
"$ 876.435" ==> 876.435
Esempio: https://dotnetfiddle.net/IrtqVt
Ha fatto il contrario di una delle risposte a questa domanda: Come rimuovere i numeri dalla stringa usando Regex.Replace?
// Pull out only the numbers from the string using LINQ
var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
var numericVal = Int32.Parse(numbersFromString);
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
Ahmad Mageed fornisce qui un approccio interessante , usa Regex e stringbuilder per estrarre gli interi nell'ordine in cui appaiono nella stringa.
Un esempio che utilizza Regex.Split basato sul post di Ahmad Mageed è il seguente:
var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;
int.TryParse(finalresult, out DayDateInt);
ecco la mia soluzione
string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
if (char.IsDigit(str))
numer += str.ToString();
else
alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();
Dovrai utilizzare Regex come \d+
\d corrisponde alle cifre nella stringa specificata.
static string GetdigitFromString(string str)
{
char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] inputArray = str.ToCharArray();
string ext = string.Empty;
foreach (char item in inputArray)
{
if (refArray.Contains(item))
{
ext += item.ToString();
}
}
return ext;
}
string s = "kg g L000145.50\r\n";
char theCharacter = '.';
var getNumbers = (from t in s
where char.IsDigit(t) || t.Equals(theCharacter)
select t).ToArray();
var _str = string.Empty;
foreach (var item in getNumbers)
{
_str += item.ToString();
}
double _dou = Convert.ToDouble(_str);
MessageBox.Show(_dou.ToString("#,##0.00"));
Usando la risposta di @ tim-pietzcker dall'alto , per quanto segue funzionerà PowerShell.
PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1
Sulla base dell'ultimo esempio ho creato un metodo:
private string GetNumberFromString(string sLongString, int iLimitNumbers)
{
string sReturn = "NA";
int iNumbersCounter = 0;
int iCharCounter = 0;
string sAlphaChars = string.Empty;
string sNumbers = string.Empty;
foreach (char str in sLongString)
{
if (char.IsDigit(str))
{
sNumbers += str.ToString();
iNumbersCounter++;
if (iNumbersCounter == iLimitNumbers)
{
return sReturn = sNumbers;
}
}
else
{
sAlphaChars += str.ToString();
iCharCounter++;
// reset the counter
iNumbersCounter = 0;
}
}
return sReturn;
}