Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to split string with "," but from 2nd comma(,)
haven't tried it, but you will need something like this:
string pattern = "|\*,";
string[] result = Regex.Split(before_split, pattern);
If you are looking for skip first ',' & then split rest of the string by ',' then you can try following.
string before_split = "pune,mumbai|01234,delhi|65432,Bhopal|09231,jabalpur|0987765";
var firstPart = before_split.Substring(0, before_split.IndexOf(",", System.StringComparison.Ordinal));
var stringToProcess = before_split.Substring(before_split.IndexOf(",", System.StringComparison.Ordinal) + 1);
var stringSegments = stringToProcess.Split(',');
Console.WriteLine("{0},{1}",firstPart ,stringSegments[0]);
for (var i = 1; i < stringSegments.Length; i++)
{
Console.WriteLine(stringSegments[i]);
}
Try this, the final result is on a List finalSplit
string before_split = "pune,mumbai|01234,333,222,delhi|65432,Bhopal|09231,jabalpur|0987765";
string[] split1 = before_split.Split(',');
List<string> finalSplit = new List<string>();
string aux = "";
foreach (string s in split1)
{
if (s.IndexOf('|') == -1)
aux = aux + s + ',';
else
{
if (aux == "")
aux = s;
else
aux = aux + s;
finalSplit.Add(aux);
aux = "";
}
}
Hope it helps
My solution is
string before_split = "pune,mumbai|01234,delhi|65432,Bhopal|09231,123,jabalpur|0987765";
string buffer = "";
var parts = before_split.Split(',');
var lines = parts.Select(p =>
{
if (p.Contains('|'))
{
var line = buffer == "" ? p : buffer + ',' + p;
buffer = "";
return line;
}
else
{
buffer = buffer == "" ? p : buffer + ',' + p;
return null;
}
}).Where(p => p != null).ToArray();
How about this...
Regex rex = new Regex("[a-zA-Z]+[a-zA-Z,]*[|]+[0-9]+");
var result = rex.Matches("pune,mumbai|01234,delhi|65432,Bhopal|09231,jabalpur|0987765").Cast<Match>()
.Select(m => m.Value)
.ToArray()
var result =before_split.Split(',')
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In C# I am passing a single string value to a function. The value is similar to this: "XA=12345678;BK=AZ31" or "XA=87654321", sometimes the BK= is there, sometimes it is not. But if it's present, I need it for my function.
I've made this attempt:
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
string XA_EQ = "";
string BK_EQ = "";
foreach(string item in item_list)
{
BK_EQ = "";
string[] split = item.Split(';');
XA_EQ = split[0];
if(split.length == 2)
BK_EQ = split[1];
my_func(XA_EQ, BK_EQ);
}
Is there a better way to do this? This works, but it seems inconvenient.
RegEx approach
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach (string item in item_list)
{
string XA_EQ = Regex.Match(item, "(?<=XA=)[0-9A-Z]*").Value;
string BK_EQ = Regex.Match(item, "(?<=BK=)[0-9A-Z]*").Value;
my_func(XA_EQ, BK_EQ);
}
https://dotnetfiddle.net/6xgBi3
I suggest Splitting initial strings into Dictionary:
using System.Linq;
...
private static Dictionary<string, string> GetVariables(string source) {
return source
.Split(';')
.Select(pair => pair.Split('='))
.ToDictionary(pair => pair[0].Trim(), pair => pair[1].Trim());
}
Now we can analyze values:
string[] item_list = new string[] { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list) {
var namesAndValues = GetVariables(item);
// If we have XA variable, assign its value to XA_EQ, otherwise assign ""
string XA_EQ = namesAndValues.TryGetValue("XA", out string xa) ? xa : "";
// If we have "BK" variable, call my_func with it
if (namesAndValues.TryGetValue("BK", out string BK_EQ)) {
// If we have "BK" variable
my_func(XA_EQ, BK_EQ);
}
}
Easy to read solution with LINQ:
string[] itemList = { "XA=12345678;BK=AZ31", "XA=87654321" };
itemList.Select(x => x.Split(";")).ToList().ForEach(i =>
{
string XA_EQ = i.FirstOrDefault();
string BK_EQ = i.Skip(1).FirstOrDefault();
my_func(XA_EQ, BK_EQ != null ? BK_EQ : "");
});
You don't get the actual value of XA or BK this way, but since you mention that this works for you I'm implementing the same logic.
string[] item_list = { "XA=12345678;BK=AZ31", "XA=87654321" };
foreach(string item in item_list)
{
if item.Contains('BK') {
string[] split = item.split(';');
my_func(split[0], split[1]);
} else {
my_func(item, null);
}
}
I have some problems to format strings from a List<string>
Here's a picture of the List values:
Now I managed to manipulate some of the values but others not, here's what I used to manipulate:
string prepareStr(string itemToPrepare) {
string first = string.Empty;
string second = string.Empty;
if (itemToPrepare.Contains("\"")) {
first = itemToPrepare.Replace("\"", "");
}
if (first.Contains("-")) {
int beginIndex = first.IndexOf("-");
second = first.Remove(beginIndex, first.Length - beginIndex);
}
return second;
}
Here's a picture of the Result:
I need to get the clear Path without the (-startup , -minimzed , MSRun , double apostrophes).
What am I doing wrong here?
EDIT my updated code:
void getStartUpEntries() {
var startEntries = StartUp.getStartUp();
if (startEntries != null && startEntries.Count != 0) {
for (int i = 0; i < startEntries.Count; i++) {
var splitEntry = startEntries[i].Split(new string[] { "||" }, StringSplitOptions.None);
var str = splitEntry[1];
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
var finishedPath = match.Groups["path"].ToString();
if (!string.IsNullOrEmpty(finishedPath)) {
if (File.Exists(finishedPath) || Directory.Exists(finishedPath)) {
var _startUpObj = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(finishedPath));
_startUpList.Add(_startUpObj);
}
else {
var _startUpObjNo = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjNo);
}
}
var _startUpObjLast = new StartUp(splitEntry[0], splitEntry[1],
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjLast);
}
lstStartUp.ItemsSource = _startUpList.OrderBy(item => item.Name).ToList();
}
You could use a regex to extract the path:
var str = #"0Raptr||""C:\Program Files (x86)\Raptr\raptrstub.exe"" --startup"
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
Console.WriteLine(match.Groups["path"]);
This will match any (even empty) text (either an escaped quote, or any character which is not a quote) between two quote characters preceeded by two pipe characters.
Similarly, you could simply split on the double quotes as I see that's a repeating occurrence in your examples and take the second item in the split array:
var path = new Regex("\"").Split(s)[1];
This is and update to your logic without using any Regex:
private string prepareStr(string itemToPrepare)
{
string result = null;
string startString = #"\""";
string endString = #"\""";
int startPoint = itemToPrepare.IndexOf(startString);
if (startPoint >= 0)
{
startPoint = startPoint + startString.Length;
int EndPoint = itemToPrepare.IndexOf(endString, startPoint);
if (EndPoint >= 0)
{
result = itemToPrepare.Substring(startPoint, EndPoint - startPoint);
}
}
return result;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a problem HtmlAgilityPack, I would like the following image. but it does not coincide with the lines. What can I do?
HtmlWeb web = new HtmlWeb();
web.OverrideEncoding = Encoding.GetEncoding("windows-1254");
HtmlAgilityPack.HtmlDocument doc = web.Load("http://www.yerelnet.org.tr/belediyeler/belediye.php?belediyeid=129531");
var nufus = doc.DocumentNode.SelectNodes("/html/body/center/table/tr/td[2]/table/tr[2]/td[2]/table/tr[2]/td/table/tr/td/table[5]/tr/td[2]/table/tr/td[3]/table[2]");
string str = String.Empty;
string line = String.Empty;
if (nufus != null)
{
for (int i = 0; i < nufus.Count; i++)
{
str += nufus[i].InnerText.Replace(" ", "").Replace("\t", "").Replace("Nüfus Bilgileri", "");
string[] s = str.Split('\n');
for (int x = 10; x < s.Count(); x++)
{
if (s[x] != String.Empty && s[x] != " ")
{
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
lnufus.Add(s[x].ToString());
}
}
}
}
dataGridView1.DataSource = lnufus.GroupBy(x => x).Select(g => new
{
Yıl = g.Key, Toplam = g.Key, Kadin = g.Key, Erkek = g.Key
}).ToList();
No need for that strange xpath query. This should work
var nufus = doc.DocumentNode.SelectNodes("//table[#class='belediyeler']/tr")
.Skip(1)
.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())
.Select(td => new { Yil = td[0], Toplam = td[1], Kadin = td[2], Erkek = td[3] })
.ToList();
dataGridView1.DataSource = nufus;
This is a rough one to explain. What I have is a string,
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
I need to turn this into
Operations|325
Operations|65
Operations|0
Operations|10
Operations|400
The problem is i need this so be dynamic to if it has 10 splits I need it to do the same process 10 times, if it has 4, then it needs to do 4.
Any help would be awesome.
Sorry for any confusion, Operations is just this string, so it's not static. It really need to be [0] of the string split.
Something like:
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
List<string> result = new List<string>();
if(splitStart.Length > 1)
for(int i = 1; i < splitStart.Length; i++)
{
result.Add(splitStart[0] + "|" + splitStart[i]);
}
If it is the strings you want, a little Linq should be fine:
string startString = "Operations\t325\t65\t0\t10\t400";
var operations = startString.Split('\t').Select(str => "Operations|" + str);
How about this?
var reFormatted = new List<string>();
foreach (var roughOne in toExplain)
{
// example of roughOne "Operations\t325\t65\t0\t10\t400"
var segments = roughOne.Split("\t");
var firstSegment = segments.First();
var sb = new StringBuilder();
foreach (var otherSegment in segments.Skip(1))
{
sb.Append(firstSegment);
sb.Append("|")
sb.Append(otherSegment);
sb.Append("\r\n");
}
reFormatted.Add(sb.ToString());
}
I was wondering how I'd get rid of periods in a filename if i have a filename like:
Test....1.txt to look like Test 1.txt ? I do NOT want files like : 1.0.1 Test.txt to be touched. Only files with consecutive periods should be replaced with a space. Any ideas?
This is my current code but as you can see, it replaces every period aside from periods in extension names:
public void DoublepCleanUp(List<string> doublepFiles)
{
Regex regExPattern2 = new Regex(#"\s{2,}");
Regex regExPattern4 = new Regex(#"\.+");
Regex regExPattern3 = new Regex(#"\.(?=.*\.)");
string replace = " ";
List<string> doublep = new List<string>();
var filesCount = new Dictionary<string, int>();
try
{
foreach (string invalidFiles in doublepFiles)
{
string fileOnly = System.IO.Path.GetFileName(invalidFiles);
string pathOnly = System.IO.Path.GetDirectoryName(fileOnly);
if (!System.IO.File.Exists(fileOnly))
{
string filewithDoublePName = System.IO.Path.GetFileName(invalidFiles);
string doublepPath = System.IO.Path.GetDirectoryName(invalidFiles);
string name = System.IO.Path.GetFileNameWithoutExtension(invalidFiles);
//string newName = name.Replace(".", " ");
string newName = regExPattern4.Replace(name, replace);
string newName2 = regExPattern2.Replace(newName, replace);
string filesDir = System.IO.Path.GetDirectoryName(invalidFiles);
string fileExt = System.IO.Path.GetExtension(invalidFiles);
string fileWithExt = newName2 + fileExt;
string newPath = System.IO.Path.Combine(filesDir, fileWithExt);
System.IO.File.Move(invalidFiles, newPath);
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = doublepPath;
clean.Cells[1].Value = filewithDoublePName;
clean.Cells[2].Value = fileWithExt;
dataGridView1.Rows.Add(clean);
}
else
{
if (filesCount.ContainsKey(fileOnly))
{
filesCount[fileOnly]++;
}
else
{
filesCount.Add(fileOnly, 1);
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(fileOnly),
filesCount[fileOnly].ToString(),
System.IO.Path.GetExtension(fileOnly));
string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fileOnly), newFileName);
System.IO.File.Move(fileOnly, newFilePath);
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = fileOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}
}
}
}
catch(Exception e)
{
//throw;
StreamWriter doublepcleanup = new StreamWriter(#"G:\DoublePeriodCleanup_Errors.txt");
doublepcleanup.Write("Double Period Error: " + e + "\r\n");
doublepcleanup.Close();
}
}
string name = "Text...1.txt";
Regex r = new Regex("[.][.]+");
string result = r.Replace(name, " ");
Well, to do that with a string:
string st = "asdf..asdf...asfd...asdf.asf.asdf.s.s";
Regex r = new Regex("\\.\\.+");
st = r.Replace(st, " ");
This will replace any instance of 2 or more '.'s with a space.
I would throw this into a method:
public static string StringReplace(string original,
string regexMatch, string replacement) {
Regex r = new Regex(regexMatch);
return r.Replace(original, replacement);
}
How about this?
string newFileName = String.Join(".", fileName.Split('.').Select(p => !String.IsNullOrEmpty(p) ? p : " ").ToArray())
Why not use something like this?
string newName = name;
while (newName.IndexOf("..") != -1)
newName = newName.Replace("..", " ");
static string CleanUpPeriods(string filename)
{
StringBuilder sb = new StringBuilder();
if (filename.Length > 0) sb.Append(filename[0]);
for (int i = 1; i < filename.Length; i++)
{
char last = filename[i - 1];
char current = filename[i];
if (current != '.' || last != '.') sb.Append(current);
}
return sb.ToString();
}
You could use use regular expressions, something like this
string fileName = new Regex(#"[.][.]+").Replace(oldFileName, "");
Continuing from dark_charlie's solution, isn't
string newName = name;
while (newName.IndexOf("..") != -1)
newName = newName.Replace("..", ".");
enough?
I have tested this code on a number of cases, and it appears to exhibit the requested behavior.
private static string RemoveExcessPeriods(string text)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
// If there are no consecutive periods, then just get out of here.
if (!text.Contains(".."))
return text;
// To keep things simple, let's separate the file name from its extension.
string extension = Path.GetExtension(text);
string fileName = Path.GetFileNameWithoutExtension(text);
StringBuilder result = new StringBuilder(text.Length);
bool lastCharacterWasPeriod = false;
bool thisCharacterIsPeriod = fileName.Length > 0 && fileName[0] == '.';
bool nextCharacterIsPeriod;
for (int index = 0; index < fileName.Length; index++)
{
// Includes both the extension separator and other periods.
nextCharacterIsPeriod = fileName.Length == index + 1 || fileName[index + 1] == '.';
if (!thisCharacterIsPeriod)
result.Append(fileName[index]);
else if (thisCharacterIsPeriod && !lastCharacterWasPeriod && !nextCharacterIsPeriod)
result.Append('.');
else if (thisCharacterIsPeriod && !lastCharacterWasPeriod)
result.Append(' ');
lastCharacterWasPeriod = thisCharacterIsPeriod;
thisCharacterIsPeriod = nextCharacterIsPeriod;
}
return result.ToString() + extension;
}
I just made a change to handle some edge cases. Here are some test results for this version.
"Test....1.txt" => "Test 1.txt"
"1.0.1..Test.txt" => "1.0.1 Test.txt"
"Test......jpg" => "Test .jpg"
"Test.....jpg" => "Test .jpg"
"one.pic.jpg" => "one.pic.jpg"
"one..pic.jpg" => "one pic.jpg"
"one..two..three.pic.jpg" => "one two three.pic.jpg"
"one...two..three.pic.jpg" => "one two three.pic.jpg"
"one..two..three.pic..jpg" => "one two three.pic .jpg"
"one..two..three..pic.jpg" => "one two three pic.jpg"
"one..two..three...pic...jpg" => "one two three pic .jpg"
Combining some other answers...
static string CleanUpPeriods(string filename)
{
string extension = Path.GetExtension(filename);
string name = Path.GetFileNameWithoutExtension(filename);
Regex regex = new Regex(#"\.\.+");
string s = regex.Replace(name, " ").Trim();
if (s.EndsWith(".")) s = s.Substring(0, s.Length - 1);
return s + extension;
}
Sample Output
"Test........jpg" -> "Test.jpg"
"Test....1.jpg" -> "Test 1.jpg"
"Test 1.0.1.jpg" -> "Test 1.0.1.jpg"
"Test..jpg" -> "Test.jpg"
void ReplaceConsecutive(string src, int lenght, string replace)
{
char last;
int count = 0;
StringBuilder ret = new StringBuilder();
StringBuilder add = new StringBuilder();
foreach (char now in src)
{
if (now == last)
{
add.Append(now);
if (count > lenght)
{
ret.Append(replace);
add = new StringBuilder();
}
count++;
}
else
{
ret.Append(add);
add = new StringBuilder();
count = 0;
ret.Append(now);
}
}
return ret.ToString();
}
Untested, but this should work.
src is the string you want to check for consecutives, lenght is the number of equal chars followed by each other until they get replaced with replace.
This is AFAIK also possible in Regex, but I'm not that good with Regex's that I could do this.