How to move 12 digit numbers from richtextbox to textbox2 - c#

I want to move 12 digit numbers from richtextbox to textbox2 by a program.
I enter these words for richtextbox
sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd
I need to get only these 12 digit numbers to textbox2..
I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits
Here i use code for that
private void button2_Click(object sender, EventArgs e)
{
Regex RX = new Regex("[0-9]{1,12}$");
textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}
I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

Split with a comma, then take all items that are of length 12 and are all digits:
var richTextBox1_Text = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
Console.Write(
string.Join(",",
richTextBox1_Text.Split(',')
.Where(m=>m.Length==12 && m.All(char.IsDigit))));
# => 512025151988,512025151988,512025151988,512025151988,512025151988
See the C# demo
In your code:
textBox2.Text = string.Join(",",
richTextBox1.Text.Split(',')
.Where(m=>m.Length==12 && m.All(char.IsDigit)));
For more complex scenarios, use a \b\d{12}\b regex like this:
textBox2.Text = string.Join("\r\n",
Regex.Matches(richTextBox1.Text, #"\b\d{12}\b")
.Cast<Match>()
.Select(m => m.Value));

I have created a method that returns a collection of strings, each containing a number.
public static IEnumerable<string> SeparateNumbers(string inputText)
{
var matches = Regex.Matches(inputText, "[0-9]{12}");
foreach (Match match in matches)
{
yield return inputText.Substring(match.Index, match.Length);
}
}
You would simply use it like this. I have also added a way to comma separate them again:
string inputText = "sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd";
var separatedNumbers = SeparateNumbers(inputText)
.ToArray();
string numbersOnly = string.Join(',', separatedNumbers);
I hope this helps.
Edit:
The reason that it gives you this: System.Text.RegularExpressions.MatchCollection is because of the default implementation of the ToString method, it simply gives you the full name of the type (including namespaces).
Also, if you want it to match any amount of numbers up to 12, simply change the regex to [0-9]{1,12} as you did initially.

1) If you want to return all 12-digit numbers (no more, no less), your regex should be [0-9]{12}. The $ you had in your OP matches the end of a string or line, and the {1,12} in your OP matches any number of digits from 1 to 12. If the number has to be surrounded by commas or string anchors so that 13-digit numbers are not matched, your regex would look something like (?<=^|,)[0-9]{12}(?=,|$).
2) If you read this link, Regex.Matches(string) returns a MatchCollection. If you convert that to string, it is just the type name to string. You have to get to each item in the collection, like:
Match match = regex.Match(input);
while (match.Success) {
// Your logic here
match = match.NextMatch();
}
3) I think string.Split(',') is easier to use. Then, loop through the array and return all strings that are 12 characters long and are numeric. Alternatively, you could use Linq as others have pointed out.

You can simply use LINQ for this purposes. If you want to get just 512025151988:
textBox2.Text = string.Join("",richTextBox1.Text.SkipWhile(c =>
!char.IsDigit(c)).TakeWhile(char.IsDigit));
Or if you want to get all numbers (512025151988,512025151988,512025151988,512025151988,512025151988):
textBox2.Text = string.Join(",",richTextBox1.Text.Split(',')
.Select(d => string.Join("",d
.SkipWhile(c => !char.IsDigit(c)).TakeWhile(char.IsDigit))))
.TrimStart(',').TrimEnd(',');
Replace first comma with space if you need to join results with space. string.Join(" ",...

Related

Extract all numbers from string

Let's say I have a string such as 123ad456. I want to make a method that separates the groups of numbers into a list, so then the output will be something like 123,456.
I've tried doing return Regex.Match(str, #"-?\d+").Value;, but that only outputs the first occurrence of a number, so the output would be 123. I also know I can use Regex.Matches, but from my understanding, that would output 123456, not separating the different groups of numbers.
I also see from this page on MSDN that Regex.Match has an overload that takes the string to find a match for and an int as an index at which to search for the match, but I don't see an overload that takes in the above in addition to a parameter for the regex pattern to search for, and the same goes for Regex.Matches.
I guess the approach to use would be to use a for loop of some sort, but I'm not entirely sure what to do. Help would be greatly appreciated.
All you have to to use Matches instead of Match. Then simply iterate over all matches:
string result = "";
foreach (Match match in Regex.Matches(str, #"-?\d+"))
{
result += match.result;
}
You may iterate over string data using foreach and use TryParse to check each character.
foreach (var item in stringData)
{
if (int.TryParse(item.ToString(), out int data))
{
// int data is contained in variable data
}
}
Using a combination of string.Join and Regex.Matches:
string result = string.Join(",", Regex.Matches(str, #"-?\d+").Select(m => m.Value));
string.Join performs better than continually appending to an existing string.
\d+ is the regex for integer numbers;
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, #"\d+").Value;
returns a string with the very first occurence of a number in subjectString.
Int32.Parse(resultString) will then give you the number.

Regex: Get a list of id

I need to get a list of id from a string. The regex for the string is like this:
"GET_LIST( [A-Za-z0-9]{5,10}){0,100}";
When I send a string like this:
GET_LIST 1000 10001 10002
I'd like to get something like "10000 10001 10002" or better a list of id. But when I try to get this with matches.Groups[1].Value;
I only get the last id.
My code look like this actually :
public IList<string> ExctractListId(string command)
{
IList<string> id = new List<string>();
Match matches = new Regex(ReponseListeService).Match(command);
if (matches.Success)
{
string ids = matches.Groups[1].Value;
Console.WriteLine(ids);
return id;
}
return id;
}
I know that the code is not fully right, actually I just want get a list or a string with all the id
This code is for a homework and I can't use, Split(), Concat(), ...
How can I have this ?
You may use
private static string pattern = #"^GET_LIST(?:\s+([A-Za-z0-9]{4,10})){0,100}$";
private static List<string> ExtractListId(string command)
{
return Regex.Matches(command, pattern)
.Cast<Match>().SelectMany(p => p.Groups[1].Captures
.Cast<Capture>()
.Select(t => t.Value)
)
.ToList();
}
See the C# demo and a regex demo. Results:
Details
^ - matches start of string
GET_LIST - a literal substring
(?:\s+([A-Za-z0-9]{4,10})){0,100} - 0 to 100 occurrences of
\s+ - 1+ whitespaces
([A-Za-z0-9]{4,10}) - Capturing group 1: 4 to 10 alphanumeric ASCII chars
$ - end of string.
Note that we have a capturing group (([A-Za-z0-9]{4,10})) inside a quantified non-capturing group (?:...){0,100}. To get those values, you should access the group capture collection. As the group has ID 1, you need to get match.Groups[1] and access all its .Captures.
You can also use the String.Split() method to split the string on whitespace characters, and then return all items that can be parsed to an int. Note that this will return all items that are valid integers, so it will work with your sample input, but if you have other types of input it may need some modification.
public static IList<string> ExctractListId(string command)
{
if (command == null || !command.StartsWith("GET_LIST"))
{
return new List<string>();
}
int temp;
return command.Split().Where(item => int.TryParse(item, out temp)).ToList();
}
Example usage:
private static void Main()
{
Console.WriteLine(string.Join(", ", ExctractListIds("GET_LIST 1000 10001 10002")));
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
The data your are searching contains white-space. So in the regex add white-space or \s and try again.
Hope this helps.
Sorry, I counldn't completely understand the problem.
A small code snippet using Javascript
function getId(data){
var regex = /^GET_LIST(([\d\s]{5,10}){0,100})/g;
var match = regex.exec(data);
console.log(match[1]);
}

get an special Substring in c#

I need to extract a substring from an existing string. This String starts with uninteresting characters (include "," "space" and numbers) and ends with ", 123," or ", 57," or something like this where the numbers can change. I only need the Numbers.
Thanks
public static void Main(string[] args)
{
string input = "This is 2 much junk, 123,";
var match = Regex.Match(input, #"(\d*),$"); // Ends with at least one digit
// followed by comma,
// grab the digits.
if(match.Success)
Console.WriteLine(match.Groups[1]); // Prints '123'
}
Regex to match numbers: Regex regex = new Regex(#"\d+");
Source (slightly modified): Regex for numbers only
I think this is what you're looking for:
Remove all non numeric characters from a string using Regex
using System.Text.RegularExpressions;
...
string newString = Regex.Replace(oldString, "[^.0-9]", "");
(If you don't want to allow the decimal delimiter in the final result, remove the . from the regular expression above).
Try something like this :
String numbers = new String(yourString.TakeWhile(x => char.IsNumber(x)).ToArray());
You can use \d+ to match all digits within a given string
So your code would be
var lst=Regex.Matches(inp,reg)
.Cast<Match>()
.Select(x=x.Value);
lst now contain all the numbers
But if your input would be same as provided in your question you don't need regex
input.Substring(input.LastIndexOf(", "),input.LastIndexOf(","));

Get specific numbers from string

In my current project I have to work alot with substring and I'm wondering if there is an easier way to get out numbers from a string.
Example:
I have a string like this:
12 text text 7 text
I want to be available to get out first number set or second number set.
So if I ask for number set 1 I will get 12 in return and if I ask for number set 2 I will get 7 in return.
Thanks!
This will create an array of integers from the string:
using System.Linq;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string text = "12 text text 7 text";
int[] numbers = (from Match m in Regex.Matches(text, #"\d+") select int.Parse(m.Value)).ToArray();
}
}
Try using regular expressions, you can match [0-9]+ which will match any run of numerals within your string. The C# code to use this regex is roughly as follows:
Match match = Regex.Match(input, "[0-9]+", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// here you get the first match
string value = match.Groups[1].Value;
}
You will of course still have to parse the returned strings.
Looks like a good match for Regex.
The basic regular expression would be \d+ to match on (one or more digits).
You would iterate through the Matches collection returned from Regex.Matches and parse each returned match in turn.
var matches = Regex.Matches(input, "\d+");
foreach(var match in matches)
{
myIntList.Add(int.Parse(match.Value));
}
You could use regex:
Regex regex = new Regex(#"^[0-9]+$");
you can split the string in parts using string.Split, and then travese the list with a foreach applying int.TryParse, something like this:
string test = "12 text text 7 text";
var numbers = new List<int>();
int i;
foreach (string s in test.Split(' '))
{
if (int.TryParse(s, out i)) numbers.Add(i);
}
Now numbers has the list of valid values

regexp for find number in a string

I have the following string fromat:
session=11;reserID=1000001
How to get string array of number?
My code:
var value = "session=11;reserID=1000001";
var numbers = Regex.Split(value, #"^\d+");
You probably were on the right track but forgot the character class:
Regex.Split(value, #"[^\d]+");
You can also write it shorter by using \D+ which is equivalent.
However, you'd get an empty element at the start of the returned array, so caution when consuming the result. Sadly, Regex.Split() doesn't have an option that removes empty elements (String.Split does, however). A not very pretty way of resolving that:
Regex.Replace(value, #"[^\d;]", "").Split(';');
based on the assumption that the semicolon is actually the relevant piece where you want to split.
Quick PowerShell test:
PS> 'session=11;reserID=1000001' -replace '[^\d;]+' -split ';'
11
1000001
Another option would be to just skip the element:
Regex.Split(...).Skip(1).ToArray();
Regex
.Matches("session=11;reserID=1000001", #"\d+") //match all digit groupings
.Cast<Match>() //promote IEnumerable to IEnumerable<Match> so we can use Linq
.Select(m => m.Value) //for each Match, select its (string) Value
.ToArray() //convert to array, as per question
.Net has built in feature without using RegEx.Try System.Web.HttpUtility.ParseQueryString, passing the string. You would need to reference the System.Web assembly, but it shouldn't require a web context.
var value = "session=11;reserID=1000001";
NameValueCollection numbers =
System.Web.HttpUtility.ParseQueryString(value.Replace(";","&"));
I will re-use my code from another question:
private void button1_Click(object sender, EventArgs e)
{
string sauce = htm.Text; //htm = textbox
Regex myRegex = new Regex(#"[0-9]+(?:\.[0-9]*)?", RegexOptions.Compiled);
foreach (Match iMatch in myRegex.Matches(sauce))
{
txt.AppendText(Environment.NewLine + iMatch.Value);//txt= textbox
}
}
If you want to play around with regex here is a good site: http://gskinner.com/RegExr/
They also have a desktop app: http://gskinner.com/RegExr/desktop/ - It uses adobe air so install that first.
var numbers = Regex.Split(value, #".*?(.\d+).*?");
or
to return each digit:
var numbers = Regex.Split(value, #".*?(\d).*?");

Categories