How to split string in C# - asp.net

I have a string and I want to get this sub string. [ 10:30 to 11:30 ] .
I don't how to do it.
strong text
string a = "This is my string at -10:30 to 11:30-";

You need to use IndexOf and LastIndexOf to get the first and the last dash.
var firstDash = a.IndexOf("-");
var lastDash = a.LastIndexOf("-");
var timePeriod = a.Substring(firstDash + 1, lastDash - 1);
That should be it. Play with +1 and -1 in case I missed where the reading starts for the substring method.
You might also want to check for the result of firstDash and lastDash. If the value for any of them is -1 then the target string or character was not found.

You can get your desired string using Regex. Try below code to do that.
Regex example: Regex Test Link
CODE:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string a = "This is my string at -10:30 to 11:30-";
string pat = #"[0-9]{2}:[0-9]{2}\sto\s[0-9]{2}:[0-9]{2}";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(a);
if(m.Success){
Console.WriteLine(m.Value);
}
else
{
Console.WriteLine("Nothing");
}
}
}

Let me give you the simplest code. The regex is same as the above.
String result = Regex.Match(a, "[0-9]{2}:[0-9]{2}\s*to\s*[0-9]{2}:[0-9]{2}").ToString();

Related

Regex is not working for particular string

I have to find these string using regex:-
(APP12345-85)
(APP12345XDP-85)
(APP12345X-85)
(APP12345-85) - not working for this one
(APP12345) - not working for this one
the original text is like this
.......some text 123 (APP12345-85) some text...............
My code is:-
Regex rgx = new Regex(#"(APP|REG)[0-9]{5}[A-Z]{5}-[0-9]{2}", caseIgnore);
MatchCollection matches = rgx.Matches(#evalString);
if (matches.Count > 0)
{
//code
}
Any help will be appreciated.
You can also match these entries with
\b(APP|REG)[0-9]{5}[A-Z]{0,5}(?:-[0-9]{2})?\b
Looks like the uppercase letters are optional, so setting to {0,5} looks safe.
And this regex does not check the beginning/end of the string/line.
See demo.
UPDATE:
Here is a sample code for the updated example:
Regex rgx = new Regex(#"\((APP|REG)[0-9]{5}[A-Z]{0,5}(?:-[0-9]{2})?\)", RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches("(APP12345-85)");
if (matches.Count > 0)
{
//code
}
Output of matches:

Split the string of a row of datatable in asp.net

I am using asp.net. I am trying to split the data which is in datatable. I have a code sample like this:
{ dt=objErrorLoggingDataAccess.GetErrorDetails(errorID);
string[] stringSeparators = new string[] { "Message" };
string error = dt.Rows[0]["Message"].ToString();
string[] test = error.Split(stringSeparators, StringSplitOptions.None);
string PageName = test[0].ToString();
PageNameLabel.Text = PageName;
stringSeparators=new string[] {HttpContext.Current.Request.Url.ToString()};
error = dt.Rows[0]["Message"].ToString();
test = error.Split(stringSeparators, StringSplitOptions.None);
string Message = test[0].ToString();
MessageLabel.Text = Message;}
in the datatable following data is there:
{....ID.......Message.......................................................................................................................
....1........http://localhost:10489/images/CategoryIcon/images Message : File does not exist. UserName: naresh#naresh.com
....2........http://localhost:10489/images/CategoryIcon/images Message : File does not exist. UserName: iswar#iswar.com}
My problem is: how can I split the Message and store in the label? I want
{http://localhost:10489/images/CategoryIcon/images}
separately and UserName separately and the message separately. How can I do that? By executing the above code I am able to split
{ http://localhost:10489/images/CategoryIcon/images
}
only. How can I split the Message column and store in pageLabel, MessageLabel, UserNamelabel?
I would use a regular expression in this case. Because only by splitting this string looks a little bit to inflexible to me.
I tested your data example against this quick and dirty RegEx:
(?<id>\d+)\.*(?<url>\w+:\/\/[\w#][\w.:#]+\/?[\w\.?=%&=\-#/$,]*)\s*Message\s*:\s*(?<message>.*)UserName:\s*(?<username>([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))
It supports valid URLs and EMail patterns.
Regex regex = new Regex(
"(?<id>\\d+)\\.*(?<url>\\w+:\\/\\/[\\w#][\\w.:#]+\\/?[\\w\\.?"+
"=%&=\\-#/$,]*)\\s*Message\\s*:\\s*(?<message>.*)UserName:\\s"+
"*(?<username>([a-zA-Z0-9_\\-\\.]+)#((\\[[0-9]{1,3}\\.[0-9]{1"+
",3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|"+
"[0-9]{1,3}))",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
// Capture the first Match, if any, in the InputText
Match m = regex.Match(InputText);
// Capture all Matches in the InputText
MatchCollection ms = regex.Matches(InputText);
// Test to see if there is a match in the InputText
bool IsMatch = regex.IsMatch(InputText);
// Get the names of all the named capture groups
// I included your fields as groups: id, url, message and username
string[] GroupNames = regex.GetGroupNames();
I don't know how often you need to call this code. Maybe you get in performance troubles if you have too much data. This regex is q&d - please adjust it to your needs.

Cannot convert type "char" to "string" in Foreach loop

I have a hidden field that gets populated with a javascript array of ID's. When I try to iterate the hidden field(called "hidExhibitsIDs") it gives me an error(in the title).
this is my loop:
foreach(string exhibit in hidExhibitsIDs.Value)
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
when I hover over the .value it says it is "string". But when I change the "string exhibit" to "int exhibit" it works, but gives me an internal error(not important right now).
You need to convert string to string array to using in for loop to get strings not characters as your loop suggests. Assuming comma is delimiter character in the hidden field, hidden field value will be converted to string array by split.
foreach(string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
Value is returning a String. When you do a foreach on a String, it iterates over the individual characters in it. What does the value actually look like? You'll have to parse it correctly before you try to use the data.
Example of what your code is somewhat doing right now:
var myString = "Hey";
foreach (var c in myString)
{
Console.WriteLine(c);
}
Will output:
H
e
y
You can use Char.ToString in order to convert
Link : http://msdn.microsoft.com/en-us/library/3d315df2.aspx
Or you can use this if you want convert your tab of char
char[] tab = new char[] { 'a', 'b', 'c', 'd' };
string str = new string(tab);
Value is a string, which implements IEnumerable<char>, so when you foreach over a string, it loops over each character.
I would run the debugger and see what the actual value of the hidden field is. It can't be an array, since when the POST happens, it is converted into a string.
On the server side, The Value property of a HiddenField (or HtmlInputHidden) is just a string, whose enumerator returns char structs. You'll need to split it to iterate over your IDs.
If you set the value of the hidden field on the client side with a JavaScript array, it will be a comma-separated string on the server side, so something like this will work:
foreach(string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", exhibit);
}
public static string reversewordsInsentence(string sentence)
{
string output = string.Empty;
string word = string.Empty;
foreach(char c in sentence)
{
if (c == ' ')
{
output = word + ' ' + output;
word = string.Empty;
}
else
{
word = word + c;
}
}
output = word + ' ' + output;
return output;
}

Is it Possible to Perform Addition in a Regex?

Assuming the placeholder $2 is populated with an integer, is it possible to increment it by 1?:
var strReplace = #"$2";
Regex.Replace(strInput, #"((.)*?)", strReplace);
You can use a callback version of Regex.Replace with a MatchEvaluator, see examples at:
http://msdn.microsoft.com/en-us/library/cft8645c.aspx
http://www.dotnetperls.com/regex-replace
Here's an example (ideone):
using System;
using System.Text.RegularExpressions;
class Program
{
static string AddOne(string s)
{
return Regex.Replace(s, #"\d+", (match) =>
{
long num = 0;
long.TryParse(match.ToString(), out num);
return (num + 1).ToString();
});
}
static void Main()
{
Console.WriteLine(AddOne("hello 123!"));
Console.WriteLine(AddOne("bai bai 11"));
}
}
Output:
hello 124!
bai bai 12
In standard (CS theoretic) regular expressions, it is impossible with a regular expression.
However, Perl and such have extensions to Regular Expressions, which has implications for their behaviour, and I am not familiar enough with them to definitely say that the extended regexes will not do it, but I'm fairly sure that this behaviour is not possible with a regex.
It's not possible with a standard regular expression but you can if you write a custom MatchEvaluator.
string str = "Today I have answered 0 questions on StackOverlow.";
string pattern = #"\w*?(\d)";
var result = Regex.Replace(str, pattern,
m => (int.Parse(m.Groups[0].Value)+1).ToString() );
Console.WriteLine(result);
Today I have answered 1 questions on StackOverlow.

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I donĀ“t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}

Resources