ProfilePageList is the string array with each string containing pageID, PageName and PageContent separated by group of characters (#$%). This is a ASP.NET application using C#
foreach (string item in ProfilePageList)
{
string PageContent = ""; string PageName = ""; string PageID = "";
*** > This part is wrong. Help me here ***
PageID = item.Substring(0, item.IndexOf('#$%') + 2);
PageContent = item.Substring(item.IndexOf('#$%') + 1);
PageName = item.Substring(0, item.IndexOf('#$%'));
callsomefunction(PageID , PageName, PageContent);
}
Input string is Helloo#$%<p>How are you??</p>#$%74396
I dont understand how to use this substring. Can someone help me Please!! Thanks a lot in advance..
Have a look at these:
http://msdn.microsoft.com/en-us/library/system.string.substring(v=vs.71).aspx
and
http://csharp.net-informations.com/string/csharp-string-substring.htm
But I think what you're trying to do is something like this:
string[] substrings = inputString.Split("#$%");
Anyway, the data structure you are using -- cramming data into strings -- is rather convoluted. Why not just use proper objects?
Related
I would appreciate some help on this, I am currently working on a item, the SAP CL Invoice Number is coming from CRM for example CL00131713, on my HTML view it is getting correctly mapped, however the requirement states there should be a - in the SAP CL Invoice Number. This should show as CL-00131713 like the image below:
My code is in my model.cs
public string SAPCLInvoiceNumber { get; set; }
In my organisation.cs class
result.Add(new InvoiceModel
{
SAPCLInvoiceNumber = invoice.SAPCLInvoiceNumber,
});.
Finally in my HTML I do
<tr ng-repeat="invoice in vm.invoices">
<td>
<!-- {{invoice.Number}} -->
{{invoice.SAPCLInvoiceNumber}}
</td>
I believe I need to do something like
SAPCLInvoiceNumber = string.replace("CL","CL - " + string.replace("CL", SAPCLInvoiceNumber ))
Please advise
Something like this should do the trick :
string pattern = #"CL";
string substitution = #"CL-";
string input = #"CL00131713";
Regex regex = new Regex(pattern);
string result = regex.Replace(input, substitution);
You can create an extension function to simplify the call
public static string FormatClNumber(this string cl)
{
string pattern = #"CL";
string substitution = #"CL-";
string input = cl;
Regex regex = new Regex(pattern);
return regex.Replace(input, substitution);
}
You can insert a "-" after second char if it is not there. Its a very simple and efficient code:
string s = "CL00131713"; //SAPCLInvoiceNumber
if (s != null & s.Length > 2 && s[2] != '-') s = s.Insert(2, "-");
I think this is better and more complete solution (eg. check if the string does not already contain the dash char, otherwise if you call it twice o a given value you will damage it to something like "CL--00131713").
New to Regular Expressions, I want to have the following text in my HTML and would like to replace with something else
Example HTML:
{{Object id='foo'}}
Extract the id into a variable like this:
string strId = "foo";
So far I have the following Regular Expression code that will capture the Example HTML:
string strStart = "Object";
string strFind = "{{(" + strStart + ".*?)}}";
Regex regExp = new Regex(strFind, RegexOptions.IgnoreCase);
Match matchRegExp = regExp.Match(html);
while (matchRegExp.Success)
{
//At this point, I have this variable:
//{{Object id='foo'}}
//I can find the id='foo' (see below)
//but not sure how to extract 'foo' and use it
string strFindInner = "id='(.*?)'"; //"{{Slider";
Regex regExpInner = new Regex(strFindInner, RegexOptions.IgnoreCase);
Match matchRegExpInner = regExpInner.Match(matchRegExp.Value.ToString());
//Do something with 'foo'
matchRegExp = matchRegExp.NextMatch();
}
I understand this might be a simple solution, I am hoping to gain more knowledge about Regular Expressions but more importantly, I am hoping to receive a suggestion on how to approach this cleaner and more efficiently.
Thank you
Edit:
Is this an example that I could potentially use: c# regex replace
While I am not solving my initial question with Regular Expressions, I did move into a simpler solution using SubString, IndexOf and string.Split for the time being, I understand that my code needs to be cleaned up but thought I would post the answer that I have thus far.
string html = "<p>Start of Example</p>{{Object id='foo'}}<p>End of example</p>"
string strObject = "Slider"; //Example
//When found, this will contain "{{Object id='foo'}}"
string strCode = "";
//ie: "id='foo'"
string strCodeInner = "";
//Tags will be a list, but in this example, only "id='foo'"
string[] tags = { };
//Looking for the following "{{Object "
string strFindStart = "{{" + strObject + " ";
int intFindStart = html.IndexOf(strFindStart);
//Then ending in the following
string strFindEnd = "}}";
int intFindEnd = html.IndexOf(strFindEnd) + strFindEnd.Length;
//Must find both Start and End conditions
if (intFindStart != -1 && intFindEnd != -1)
{
strCode = html.Substring(intFindStart, intFindEnd - intFindStart);
//Remove Start and End
strCodeInner = strCode.Replace(strFindStart, "").Replace(strFindEnd, "");
//Split by spaces, this needs to be improved if more than IDs are to be used
//but for proof of concept this is perfect
tags = strCodeInner.Split(new char[] { ' ' });
}
Dictionary<string, string> dictTags = new Dictionary<string, string>();
foreach (string tag in tags)
{
string[] tagSplit = tag.Split(new char[] { '=' });
dictTags.Add(tagSplit[0], tagSplit[1].Replace("'", "").Replace("\"", ""));
}
//At this point, I can replace "{{Object id='foo'}}" with anything I'd like
//What I don't show is that I go into the website's database,
//get the object (ie: Slider) and return the html for slider with the ID of foo
html = html.Replace(strCode, strView);
/*
"html" variable may contain:
<p>Start of Example</p>
<p id="foo">This is the replacement text</p>
<p>End of example</p>
*/
I have been trying real hard understanding regular expression, Is there any way I can replace character(s) that is between two regex/ For example I have
string datax = "a4726e1e-babb-4898-a5d5-e29d2bc40028;POPULATE DATA AØ99c1d133-15f5-4ef5-bc59- d9ed673b70c6;POPULATE DATA BØ";
how to remove string between regex ";" and "Ø" ???
i try to use code like this :
string xresult = Regex.Replace(datax, #"(?<=;)(\w+?)(?=Ø)", "");
But not working.
please corrected and give me solutions...
thanks...
i want the result like this sir :
string datax = "a4726e1e-babb-4898-a5d5-e29d2bc40028;Ø99c1d133-15f5-4ef5-bc59-d9ed673b70c6;Ø";
I think you need to understand regex a little better and how the replace function works. with regex you're defining capture groups, and with the replace function you want to replace those groups.
how to remove string between regex ";" and "Ø" ???
Step 1: First find ";",then capture all characters up to and including "Ø".
That's (;.*?Ø)
( New Capture Group
; Match ";"
. Match Anything
* Zero or more times
? Be Lazy
Ø Match "Ø"
) End Capture
Step 2: Replace each group with ";Ø"
public static string Replace(string input, string pattern, string
replacement)
So you need to put back the ";Ø" you removed from the original capture.
static void Test2()
{
foreach (string item in SO2588078())
{
Console.WriteLine(item);
}
string input = "a4726e1e-babb-4898-a5d5-e29d2bc40028;POPULATE DATA AØ99c1d133-15f5-4ef5-bc59- d9ed673b70c6;POPULATE DATA BØ";
string regex = "(;.*?Ø)";
string output = Regex.Replace(input, regex, ";Ø");
if (output == string.Join(";Ø", SO2588078()) + ";Ø")
{
Console.WriteLine("TRUE");
}
}
An alternative would be to parse the string without regex. It's a simple format and this gives you more control over the process so you can see what's happening, why it's gone wrong and why it gives the results it does. Since you can step through it.
private static IEnumerable<string> SO2588078()
{
string datax = "a4726e1e-babb-4898-a5d5-e29d2bc40028;POPULATE DATA AØ99c1d133-15f5-4ef5-bc59- d9ed673b70c6;POPULATE DATA BØ";
string temp = datax;
while (!string.IsNullOrEmpty(temp))
{
int index1 = temp.IndexOf(';');
if (index1 > -1)
{
string guid = temp.Remove(index1);
yield return guid;
int index2 = temp.IndexOf('Ø');
if (index2 > -1)
{
temp = temp.Substring(index2 + 1);
}
else
{
temp = null;
}
}
else
{
temp = null;
}
}
}
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.
I have got a string as follows:
string name ="C:\folder\back-201190082233.zip";
How can I get only the part 201190082233 from the string name? I have tried like this for getting the only the part 201190082233
string filetype = name;
string[] getfiledate = filetype.Split('-');
But I am getting the part 201190082233.zip. Now I want to get only the part 201190082233. Would anyone please help on this?
Seems like a good idea to use regular expressions:
var match = Regex.Match("back.201190082233.zip" , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
Edit:
If you're dealing with paths, .Net offers help:
string name = #"C:\folder\back.201190082233.zip";
var fileName = Path.GetFileName(name);
var match = Regex.Match(fileName , #"(?<=-)\d+(?=\.)");
if(match.Success)
{
var numericPart = match.Value;
}
string name = "C:\folder\back-201190082233.zip";
string filetype = name;
string[] getfiledate = filetype.Split(new[] {'.', '-'});
string datepart = getfiledate[1];
How about this way?
var fileDate= filetype.Split('.')[1];
Edit for updates
var fileDate = Path.GetFileNameWithoutExtension(filetype).Split('.')[0]
Probably
var date = Path.GetFileNameWithoutExtension( name ).Split('-')[1];
would be sufficient.
See documentation for function Path.GetFileNameWithoutExtension.
Why are you splitting with a '-' ? Shouldn't it be '.' ?
string numberPart = filetype.Split('.')[1];
You may use something like below
string str = name.Split(".")[1];
Hope this helps!!
or if the string changes you could use a mor specific regular expression like this:
string s = Regex.Replace("back.201190082233.zip", #"[^\.]+\.([^\.]+)\..*", "$1");