Extract text from string between commas - c#

I want to extract only those words between two commas.
So, if the string is Ab Java, DE, 78801 The answer must be DE
I have tried this code but it is not working
string search = "Ab Java, DE, 78801 ";
int index = search.IndexOf(",");
string result = search.Substring(search.IndexOf(",") ,index);
MessageBox.Show(result);

If your string has always 2 commas, you can use String.Split for it like;
string search = "Ab Java, DE, 78801 ";
Console.WriteLine(search.Split(',')[1]); // DE
Remember, this will you generate DE with an extra white space before it.
If you don't want that white space, you can use TrimStart() to remove it.
Console.WriteLine(search.Split(',')[1].TrimStart()); //DE

Your start and end in your Substring resolve to the same value.
Try using split and getting the second item, of course this assumes that your input always follows the pattern in your example. Otherwise you'll need to do something more complicated.
string[] searchItems = search.Split(',');
string result = searchItems[1].Trim(); // will output DE

try this
string[] splitedStr=search.Split(',');
string NewStr=splitedStr[1].ToString();

Assuming your string always has just two commas, then:
search.Split(", ")[1]
will give you the desired text.

Try this...
String str = "Ab Java, DE, 78801 ";
String[] myStrings = str.split(",");
String marco = myStrings[1];

Try This. It May work...
string[] arrayStr = search.Split(',');
int len = arrayStr.Length;
for(int i =1;i<=len-2;i++)
{
MessageBox.Show(result);
}

That is something I would have solved using regular expressions. It might be slower than the String.Split solutions but it is way easier to read - in particular if the pattern is going to evolve over time.
The solution would than look like this:
string search = "Ab Java, DE, 78801 ";
Regex r = new Regex(", *(.*?) *,", RegexOptions.Compiled);
Console.WriteLine(r.Match(search).Groups[1].ToString());
This writes DE without surrounding spaces. The regex instance should be a static member of your class, since I assume this is happening within a loop ...

Related

Extracting only the substring containing letters from a string containing digits strings and symbols

I have a string that is like the following:
string str = hello_16_0_2016;
What I want is to extract hello from the string. As in my program the string part can occur anywhere as it is autogenerated, so I cannot fix the position of my string.
For example: I can take the first five string from above and store it in a new variable.
But as occurring of letters is random and I want to extract only letters from the string above, so can someone guide me to the correct procedure to do this?
Could you just use a simple regular expression to pull out only alphabetic characters, assuming you only need a-z?
using System.Text.RegularExpressions;
var str = "hello_16_0_2016";
var onlyLetters = Regex.Replace(str, #"[^a-zA-Z]", "");
// onlyLetters = "hello"
I'd use something like this (uses Linq):
var str = "hello_16_0_2016";
var result = string.Concat(str.Where(char.IsLetter));
Check it out
Or, if performance is a concern (because you have to do this on a tight loop, or have to convert hundreds of thousands of strings), it'd probably be faster to do:
var result = new string(str.Where(char.IsLetter).ToArray());
Check it too
But as occurring of letters is random and I want to extract only
letters from the string above, so can someone guide me to the correct
procedure to do this?
The following will extract the first text, without numbers anywhere in the string:
Console.WriteLine( Regex.Match("hello_16_0_2016", #"[A-Za-z]+").Value ); // "hello"

Regex Find Replace distinct parts of a string for a porting application

If I have a line of code:
String s = "\t\tgets(buf);";
and need to convert it to
s = "\t\tbuf";
What Regex pattern would I use in the Regex.Replace() method to get rid of
gets() and leave behind buf assuming that buf is a random string. I would also like to preserve the other formatting characters etc that may exist in that string.
Apologies for editing the question.
I used:
s = Regex.Replace(s, "gets", "");
s = s.Replace("(", "").Replace(")", "").Replace(";", "").Replace(" ", "");
s += " = Console.ReadLine();";
But this wouldn't work if the line get(buf) was surrounded by some other parenthesis or
formatting like
s= "/rgets (buf)"; OR s= "(gets (buf))/n";
So I would Ideally just want to just get rid of the gets() leaving behind 'buf' and the other content in the line as is and concat to it later.
Thanks
You read the documentation. Then you write the appropriate regular expression.
string s = "\t\tgets(buf);" ;
string s1 = Regex.Replace( s , #"^(\t\t)gets\(.+)\)(;)" , #"$1$2 = Console.Readline()$3" ) ;
One might note the gets(3) takes an arbitrary expression that evaluates to a char*. That expression is not necessarily going to be an identifier or something that can be used on the left side of an assignment (as it were, an lval in the C language).
You could just use a couple methods from the string class to achieve this:
s = string.Concat(s.Replace("gets(", "").Replace(");", ""), " = Console.ReadLine();");
Regex is powerful, but can sometimes be overkill.
If you really feel you need it, then please add more details into your question.

Regex: Parse specific string with one 18-digit number

C#/.NET 4.0
I need to parse a string containing a 18-digit number. I also need the substrings at the left and right side.
Example strings:
string a = "Frl Camp Gerbesklooster 871687120000000691 OPLDN 2010 H1";
string b = "some text with spaces 123456789012345678 more text";
How it should be parsed:
string aParsed[0] = "Frl Camp Gerbesklooster";
string aParsed[1] = "871687120000000691";
string aParsed[2] = "OPLDN 2010 H1";
string bParsed[0] = "some text with spaces";
string bParsed[1] = "123456789012345678";
string bParsed[2] = "more text";
There is always that 18-digit number in the middle of the string. I'm an absolute newbie to Regex so I don't actually have a try of my own.
What is the best way to do this? Should I use regular expressions?
Thanks.
You can use something like the regex: (.*)(\d{18})(.*).
The key here is to use {18} to specify that there must be exactly 18 digits and to capture each part in a group.
var parts = Regex.Matches(s, #"(.*)(\d{18})(.*)")
.Cast<Match>()
.SelectMany(m => m.Groups.Cast<Group>().Skip(1).Select(g=>g.Value))
.ToArray();
Daniƫl,
Although the question is answered the following may be a useful reference for learning Reg Expressions.
http://txt2re.com
Regards,
Liam

Please tell me what the problem is c# regex.split()

string temp_constraint = row["Constraint_Name"].ToString();
string split_string = "FK_"+tableName+"_";
string[] words = Regex.Split(temp_constraint, split_string);
I am trying to split a string using another string.
temp_constraint = FK_ss_foo_ss_fee
split_string = FK_ss_foo_
but it returns a single dimension array with the same string as in temp_constraint
Please help
Your split operation works fine for me:
string temp_constraint = "FK_ss_foo_ss_fee";
string split_string = "FK_ss_foo_";
string[] words = Regex.Split(temp_constraint, split_string);
foreach (string word in words)
{
Console.WriteLine(">{0}<", word);
}
Output:
><
>ss_fee<
I think the problem is that your variables are not set to what you think they are. You will need to debug to find the error elsewhere in your program.
I would also avoid using Split for this (both Regex and String.Split). You aren't really splitting the input - you are removing a string from the start. Split might not always do what you want. Imagine if you have a foreign key like the following:
FK_ss_foo_ss_fee_FK_ss_foo_ss_bee
You want to get ss_fee_FK_ss_foo_ss_bee but split would give you ss_fee_ and ss_bee. This is a contrived example, but it does demonstrate that what you are doing is not a split.
You should use String.Split instead
string[] words =
temp_constraint.Split(new []{split_string}, StringSplitOptions.None);
string split uses a character array to split text and does the split by each character which is not often ideal.
The following article shows how to split text by an entire word
http://www.bytechaser.com/en/functions/ufgr7wkpwf/split-text-by-words-and-not-character-arrays.aspx

how to split a string

i have a string like 123Prefix1pics.zip
i want to split it into 123 Prefix1 pics.zip and store them in different variables
i m trying to do it in c#,.net
jst litle bit confused on how to use split method
splitArray = Regex.Split(subjectString, #"(?<=\p{N})(?=\p{L})");
will work in C# to split in positions between a number (\p{N}) and a letter (\p{L}).
If you also want to split between a letter and a number, use
splitArray = Regex.Split(subjectString, #"(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})");
however, that splits your example too much.
You only want to split that one string? Too easy!
string filename = "123Prefix1pics.zip"
string part1 = "123"
string part2 = "Prefix1"
string part3 = "pics.zip"
Ok this is a joke, but it gives the right answer. Unless you generalise your splitting rule, or provide further examples, we can only guess.
You may be asking to make a string break after a numeral, but again I'm only guessing.
You can start with:
string filename = "123Prefix1pics.zip"
string part1 = filename.Substring(0, 3);
string part2 = filename.Substring(3, 7);
string part3 = filename.Substring(10, 4);
You can also note String.Split() needs a separator argument, like an ; or ,. As you don't have any separator, you can try two approaches:
Make sure all your filenames have same format; this way, you can to use Substring() to break your strings
You can identify a more general pattern, as "numbers, 7 characters plus 4 more characters" and to use a regular expression. This is a more advanced solution and can lead to maintenance problems;
I recommend you to stick with first option.
You can split it like this:
your ip in a string variable like this:
create a char vector
then a string vector
Code:
string theIP="this is string";
char[] separator={' '}; //you can put multiple separators
string[] result = theIP.Split(separator,StringSplitOptions.None);
this means result[0] is "this", result[1] is "is", and so on.
You can find a good tutorial about string splitting here:
http://goldwin-advertising.ro/index.php?option=com_content&view=article&id=10:splitstring&catid=3:howto&Itemid=5
Good luck!
Look like you want to split by fixed size.
So use yourString.Substring(0, 3);

Categories