I tried to split a string wich contains these character #
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
but every time the array contains just one member. I've tried a lot of combinations but anything seems to work, I also tried to replace the string with a blank space and it kinda works - the problem is that it remains a single string.
domicilio = domicilio.Replace(#"#", #" ");
How can I resolve this?
Complete code:
String[] domicilioSeparado;
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
If you just want to split a string on a delimiter, in this instance '#', then you can use this:
domicilioSeparado = domicilio.Split("#");
That should give you what you want. Your second attempt simply replaces all the characters '#' in the string with ' ', which doesn't seem to be what you want. Can we see the string you're trying to split? That might help explain why it's not working.
EDIT:
Ok, here's how I think your code should look, give this a shot and let me know how it goes.
List<string> domicilioSeparado = new List<string>();
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split("#");
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
Try this:
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
Some notes:
1 - It is ('#'), instead of ("#"); 2 - Replace does not split a string, it only replace that part, keeping as a single string.
In case you want an example that includes the printing of the whole array:
string domicilio = "abc#def#ghi";
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
for (int i = 0; i < domicilioSeparado.Length; i++)
{
MessageBox.Show(domicilioSeparado[i]);
}
It will open a Message Box for each element within domicilioSeparado.
Related
For example, let's say I have this:
string test = "id:test THISISTHESTRINGIWANT id2:test"
And I want to get THISISTHESTRINGIWANT. In order to do that I was wondering if its possible to find it like this:
left_string = "id:test ", right_string = " id2"
Thank You
You can use the .split like this
string test = "id:test THISISTHESTRINGIWANT id2:test"
char[] delimiterChars = { ' '};
string[] output= test.Split(delimiterChars);
this will give you 3 strings {id:test,THISISTHESTRINGIWANT,id2:test}
you can then iterate through the string array with whatever condition you want to weed out the unwanted data or you can change the char array to include any characters you want to split on.
This seems really simple, but I have a string that I want to replace a string with a tab and 2 new lines and it isn't working.
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\n\t\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
updatedString never gets updated, it remains at "VAR_GLOBAL\n\t\nEND_VAR\n", where it should be "VAR_GLOBAL\tMyVariable : Bool\n\t\nEND_VAR\n". I'm not sure why it won't change.
While Regex might not be the best suited for such scenario, please find below a sample code which will suit your needs (Regex test).
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\\n\\t\\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
The other (maybe simplier) option would be to do a straight replace like in:
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string updatedString = newString.Replace("\n\t\n", "\t");
I have this string D:\ASN\Documents\ENU\LO\ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf and I want to exclude this string D:\ASN\Documents\ENU\LO from the above string and then get the first string(in this case ANL)after the split.
I tried something like this:
string fullpath = "D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf"
string[] sep = new string[]{"D:\\ASN\\Documents\\ENU\\LO"};
string [] result = fullpath.split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write(s.Substring(s.IndexOf(#"\") + 1));
}
But this is giving me ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf". Instead I need only ANL. How can this be achieved? Is there any other way to get this instead of this way.
TIA
var result = fullpath.Replace(samplePath, "").Split('\\')[1];
You can replace the first part (samplePath) with nothing, removing it (or you could use Substring to get the second part of the fullPath, counting the characters of samplePath), and then Split the result on '\', getting the second occurrence, which is the result you expect.
Here's a working version: https://dotnetfiddle.net/k4tfGP
Can you do a split on the second string when it sees the \?
String sampleString = "ANL\File\05003ede-59bf-45c6-bb57-a6111e9f18e0\linux-cheat-sheet.pdf"";
String[] stringArray = sampleString.split("\");
String wantedString = stringArray[0];
This is not what split() is intended for. split() is generally used to divide your string into multiple sections based on a separator. In your case, you might have wanted to use it to separate the sub-folders by splitting on '\'.
But you want something else -- to remove a section of text. If you know that the text will always be at the start, try this:
string result = fullpath.Substring("D:\\ASN\\Documents\\ENU\\LO".Length);
This will return the original string, minus the first X characters, where X is exactly the length of the string you want to remove.
string fullpath =
"D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf";
string[] sep = new string[] {"D:\\ASN\\Documents\\ENU\\LO"};
string[] result = fullpath.Split(sep, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write(s.Substring(s.IndexOf(#"\") + 1, s.IndexOf(#"\", 2) - 1));
}
String.IndexOf will get you the index of the first, but has overloads giving a starting point. So In this example, I have given the starting point as "2" as your path contains "\\" always.
string basepath = "D:\\ASN\\Documents\\ENU\\LO\\";
string fullpath = "D:\\ASN\\Documents\\ENU\\LO\\ANL\\File\\05003ede-59bf-45c6-bb57-a6111e9f18e0\\linux-cheat-sheet.pdf";
fullpath = fullpath.Replace(basepath, "");
string returnValue = fullpath.Remove(fullpath.IndexOf("\\"), fullpath.Length-fullpath.IndexOf("\\"));
Worked here...
I am trying to process a report from a system which gives me the following code
000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}
I need to extract the values between the curly brackets {} and save them in to variables. I assume I will need to do this using regex or similar? I've really no idea where to start!! I'm using c# asp.net 4.
I need the following variables
param1 = 000
param2 = GEN
param3 = OK
param4 = 1 //Q
param5 = 1 //M
param6 = 002 //B
param7 = 3e5e65656-e5dd-45678-b785-a05656569e //I
I will name the params based on what they actually mean. Can anyone please help me here? I have tried to split based on spaces, but I get the other garbage with it!
Thanks for any pointers/help!
If the format is pretty constant, you can use .NET string processing methods to pull out the values, something along the lines of
string line =
"000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}";
int start = line.IndexOf('{');
int end = line.IndexOf('}');
string variablePart = line.Substring(start + 1, end - start);
string[] variables = variablePart.Split(' ');
foreach (string variable in variables)
{
string[] parts = variable.Split('=');
// parts[0] holds the variable name, parts[1] holds the value
}
Wrote this off the top of my head, so there may be an off-by-one error somewhere. Also, it would be advisable to add error checking e.g. to make sure the input string has both a { and a }.
I would suggest a regular expression for this type of work.
var objRegex = new System.Text.RegularExpressions.Regex(#"^(\d+)=\[([A-Z]+)\] ([A-Z]+) \{Q=(\d+) M=(\d+) B=(\d+) I=([a-z0-9\-]+)\}$");
var objMatch = objRegex.Match("000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}");
if (objMatch.Success)
{
Console.WriteLine(objMatch.Groups[1].ToString());
Console.WriteLine(objMatch.Groups[2].ToString());
Console.WriteLine(objMatch.Groups[3].ToString());
Console.WriteLine(objMatch.Groups[4].ToString());
Console.WriteLine(objMatch.Groups[5].ToString());
Console.WriteLine(objMatch.Groups[6].ToString());
Console.WriteLine(objMatch.Groups[7].ToString());
}
I've just tested this out and it works well for me.
Use a regular expression.
Quick and dirty attempt:
(?<ID1>[0-9]*)=\[(?<GEN>[a-zA-Z]*)\] OK {Q=(?<Q>[0-9]*) M=(?<M>[0-9]*) B=(?<B>[0-9]*) I=(?<I>[a-zA-Z0-9\-]*)}
This will generate named groups called ID1, GEN, Q, M, B and I.
Check out the MSDN docs for details on using Regular Expressions in C#.
You can use Regex Hero for quick C# regex testing.
You can use String.Split
string[] parts = s.Split(new string[] {"=[", "] ", " {Q=", " M=", " B=", " I=", "}"},
StringSplitOptions.None);
This solution breaks up your report code into segments and stores the desired values into an array.
The regular expression matches one report code segment at a time and stores the appropriate values in the "Parsed Report Code Array".
As your example implied, the first two code segments are treated differently than the ones after that. I made the assumption that it is always the first two segments that are processed differently.
private static string[] ParseReportCode(string reportCode) {
const int FIRST_VALUE_ONLY_SEGMENT = 3;
const int GRP_SEGMENT_NAME = 1;
const int GRP_SEGMENT_VALUE = 2;
Regex reportCodeSegmentPattern = new Regex(#"\s*([^\}\{=\s]+)(?:=\[?([^\s\]\}]+)\]?)?");
Match matchReportCodeSegment = reportCodeSegmentPattern.Match(reportCode);
List<string> parsedCodeSegmentElements = new List<string>();
int segmentCount = 0;
while (matchReportCodeSegment.Success) {
if (++segmentCount < FIRST_VALUE_ONLY_SEGMENT) {
string segmentName = matchReportCodeSegment.Groups[GRP_SEGMENT_NAME].Value;
parsedCodeSegmentElements.Add(segmentName);
}
string segmentValue = matchReportCodeSegment.Groups[GRP_SEGMENT_VALUE].Value;
if (segmentValue.Length > 0) parsedCodeSegmentElements.Add(segmentValue);
matchReportCodeSegment = matchReportCodeSegment.NextMatch();
}
return parsedCodeSegmentElements.ToArray();
}
I want to replace a charecter in a string with a string in c#.
I have tried the following,
Here in the following program, i want replace set of charecters between charecters ':' and first occurance of '-' with some others charecters.
I could able to extract the set of charecters between ':' and first occurance of '-'.
Can any one say how to insert these back in the source string.
string source= "tcm:7-426-8";
string target= "tcm:10-15-2";
int fistunderscore = target.IndexOf("-");
string temp = target.Substring(4, fistunderscore-4);
Response.Write("<BR>"+"temp1:" + temp + "<BR>");
Examples:
source: "tcm:7-426-8" or "tcm:100-426-8" or "tcm:10-426-8"
Target: "tcm:10-15-2" or "tcm:5-15-2" or "tcm:100-15-2"
output: "tcm:10-426-8" or "tcm:5-426-8" or "tcm:100-426-8"
In a nutshell, I want to replace the set of charectes between ':' and '-'(firstoccurance) and the charecters extracetd from the same sort of string.
Can any help how it can be done.
Thank you.
If you want to replace the first ":Number-" from the source with the content from target, you can use the following regex.
var pattern1 = New Regex(":\d{1,3}-{1}");
if(pattern1.IsMatch(source) && pattern1.IsMatch(target))
{
var source = "tcm:7-426-8";
var target = "tcm:10-15-2";
var res = pattern1.Replace(source, pattern1.Match(target).Value);
// "tcm:10-426-8"
}
Edit: To not have your string replaced with something empty, add an if-clause before the actualy replacing.
Try a regex solution - first this method, takes the source and target strings, and performs a regex replace on the first, targetting the first numbers after the 'tcm', which must be anchored to the start of the string. In the MatchEvaluator it executes the same regex again, but on the target string.
static Regex rx = new Regex("(?<=^tcm:)[0-9]+", RegexOptions.Compiled);
public string ReplaceOneWith(string source, string target)
{
return rx.Replace(source, new MatchEvaluator((Match m) =>
{
var targetMatch = rx.Match(target);
if (targetMatch.Success)
return targetMatch.Value;
return m.Value; //don't replace if no match
}));
}
Note that no replacement is performed if the regex doesn't return a match on the target string.
Now run this test (probably need to copy the above into the test class):
[TestMethod]
public void SO9973554()
{
Assert.AreEqual("tcm:10-426-8", ReplaceOneWith("tcm:7-426-8", "tcm:10-15-2"));
Assert.AreEqual("tcm:5-426-8", ReplaceOneWith("tcm:100-426-8", "tcm:5-15-2"));
Assert.AreEqual("tcm:100-426-8", ReplaceOneWith("tcm:10-426-8", "tcm:100-15-2"));
}
I'm not clear on the logic used to decide which bit from which string is used, but still, you should use Split(), rather than mucking about with string offsets:
(note that the Remove(0,4) is there to remove the tcm: prefix)
string[] source = "tcm:90-2-10".Remove(0,4).Split('-');
string[] target = "tcm:42-23-17".Remove(0,4).Split('-');
Now you have the numbers from both source and target in easy-to-access arrays, so you can build the new string any way you want:
string output = string.Format("tcm:{0}-{1}-{2}", source[0], target[1], source[2]);
Heres without regex
string source = "tcm:7-426-8";
string target = "tcm:10-15-2";
int targetBeginning = target.IndexOf("-");
int sourceBeginning = source.IndexOf("-");
string temp = target.Substring(0, targetBeginning);//tcm:10
string result = temp + source.Substring(sourceBeginning, source.Length-sourceBeginning); //tcm:10 + -426-8