I need to get all numbers from a string like this:
"156234 something 567345 another thing 45789 anything"
The result should be a collection of numbers having:
156234, 567345, 45789
I tried @"\\d+"
, but it will only give me 156234
.
EDIT: The numbers are integers, however they can also occur like this "156234 something 567345 another thing 45789 anything2345". In this case I only need the integers ie 156234, 567345, 45789 and not 156234, 567345, 45789,2345.
Also the integers which i dont want will always be preceed with a text for ex:anything2345.
Everything is ok with your regex, you just need to come through all the matches.
Regex regex = new Regex(@"\d+");
foreach (Match match in regex.Matches("156234 something 567345 another thing 45789 anything"))
{
Console.WriteLine(match.Value);
}
You want to split on the characters, not the digits. Use the capital D
string[] myStrings = Regex.Split(sentence, @"\D+");
If 2345 should not be matched in your revised sample string (156234 something 567345 another thing 45789 anything2345), you could use Dima's solution but with the regex:
\b\d+\b
This assures that the number is surrounded by word boundaries.
This'z in java. You don't actually need a Regex.. just a normal replaceAll should do the trick for you! : For ex : You can strip off the Non-Digits, and then split and calculate the sum.
public static int getSumOfNumbers(String s) {
int sum = 0;
String x = s.replaceAll("\\D+", " ");
String[] a = x.split(" ");
for(int i = 0; i < a.length; i++)
sum += Integer.parseInt(a[i]);
System.out.println(x + " : and sum is : "+sum);
return sum;
}
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.