Pick up relevant information from a string using regular expression C#3.0 - c#-3.0

I have been given some file name which can be like
<filename>YYYYMMDD<fileextension>
some valid file names that will satisfy the above pattern are as under
xxx20100326.xls,
xxx2v20100326.csv,
x_20100326.xls,
xy2z_abc_20100326_xyz.csv,
abc.xyz.20100326.doc,
ab2.v.20100326.doc,
abc.v.20100326_xyz.xls
In what ever be the above defined case, I need to pick up the dates only. So for all the cases, the output will be 20100326.
I am trying to achieve the same but no luck.
Here is what I have done so far
string testdata = "x2v20100326.csv";
string strYYYY = #"\d{4}";
string strMM = #"(1[0-2]|0[1-9])";
string strDD = #"(3[0-1]|[1-2][0-9]|0[1-9])";
string regExPattern = #"\A" + strYYYY + strMM + strDD + #"\Z";
Regex regex = new Regex(regExPattern);
Match match = regex.Match(testdata);
if (match.Success)
{
string result = match.Groups[0].Value;
}
I am using c#3.0 and dotnet framework 3.5
Please help. It is very urgent
Thanks in advance.

Try this:
DateTime result = DateTime.MinValue;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
var testString = "x2v20100326.csv";
var format = "yyyyMMdd";
try
{
for (int i = 0; i < testString.Length - format.Length; i++)
{
if (DateTime.TryParseExact(testString.Substring(i, format.Length), format, provider, System.Globalization.DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", testString, result.ToString());
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", testString);
}

This one fetches the last date in the string.
var re = new Regex("(?<date>[0-9]{8})");
var test = "asdf_wef_20100615_sdf.csv";
var datevalue = re.Match(test).Groups["date"].Value;
Console.WriteLine(datevalue); // prints 20100615

Characters \A and \Z - begin and end of the string respectivly.
I think you need pattern like:
string regExPattern = #"\A.*(?<FullDate>" + strYYYY + strMM + strDD + #").*\..*\Z";
".*" - any symbols at the begin
".*\..*" - any symbols before the dot, dot and any symbols after dot
And get a full date:
match.Groups["FullDate"]

You may need to group things in your month and day expressions:
((1[0-2])|(0[1-9))
((3[0-1])|([1-2][0-9])|(0[1-9]))

Related

Flutter - How to delete text after last '/' in string

I need help transforming this:
/storage/emulated/0/Android/data/testapp/files/textToDelete
into this
/storage/emulated/0/Android/data/testapp/files/
note: I don't want to use static value substring
// the string to be trimmed
var myString = '/storage/emulated/0/Android/data/testapp/files/textToDelete';
// substring the string using the last index of the character + 1
var trimmedString = myString.substring(0, myString.lastIndexOf('/') + 1);
// print the trimmed string
print(trimmedString);
OUTPUT:
/storage/emulated/0/Android/data/testapp/files/
Used
.substring(0, var.lastIndexOf('/'));
and that worked perfectly

how to convert string to time formatted in flutter

I have data from database "192624". how I can change the String format in flutter become time formatted. example "192624" become to "19:26:24". I try using intl packages is not my hope result.
this my code
DateTime inputDate = inputDate;
String formattedTime = DateFormat.Hms().format(inputDate);
in above is not working
I want result convert data("192624") to become "19:26:24". data time from database.
use this method
String a() {
var a = "192624".replaceAllMapped(
RegExp(r".{2}"), (match) => "${match.group(0)}:");
var index = a.lastIndexOf(":");
a = a.substring(0,index);
return a;
}
Have you checked out this a answer :
String time;
// call this upper value globally
String x = "192624";
print(x.length);
x = x.substring(0, 2) + ":" + x.substring(2, 4)+":"+x.substring(4,x.length);
time =x;
print(x);
just globally declare the string and then assign the local String to global then call it in the ui

Javascript First letter uppercase restlower of two lines "."

I want to first letter to be in upper case other in lower. But after ".", it must be upper again..
function firstToUpperCase( str ) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
var str = 'prompt("Enter text to convert: ")
var Upcase = firstToUpperCase( str );
document.write(Upcase);
Here's a simplistic answer based on what you provided. It does not take whitespace into account following the period since you didn't mention that in the specs.
function firstToUpperCase(str) {
var parts = str.split(".");
for (i = 0; i < parts.length; i++) {
parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1).toLowerCase();
}
return parts.join(".");
}
If you're trying to deal with sentences, something like this might be a little better, though it does not preserve exact whitespace:
function firstToUpperCase(str) {
var parts = str.split(".");
for (i = 0; i < parts.length; i++) {
sentence = parts[i].trim();
parts[i] = sentence.substring(0, 1).toUpperCase() + sentence.substring(1).toLowerCase();
}
return parts.join(". ");

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*

C sharp delimiter

In a given sentence i want to split into 10 character string. The last word should not be incomplete in the string. Splitting should be done based on space or , or .
For example:
this is ram.he works at mcity.
now the substring of 10 chars is,
this is ra.
but the output should be,
this is.
Last word should not be incomplete
You can use a regular expression that checks that the character after the match is not a word character:
string input = "this is ram.he";
Match match = Regex.Match(input, #"^.{0,10}(?!\w)");
string result;
if (match.Success)
{
result = match.Value;
}
else
{
result = string.Empty;
}
Result:
this is
An alternative approach is to build the string up token by token until adding another token would exceed the character limit:
StringBuilder sb = new StringBuilder();
foreach (Match match in Regex.Matches(input, #"\w+|\W+"))
{
if (sb.Length + match.Value.Length > 10) { break; }
sb.Append(match.Value);
}
string result = sb.ToString();
Not sure if this is the sort of thing you were looking for. Note that this could be done a lot cleaner, but should get you started ... (may want to use StringBuilder instead of String).
char[] delimiterChars = { ',', '.',' ' };
string s = "this is ram.he works at mcity.";
string step1 = s.Substring(0, 10); // Get first 10 chars
string[] step2a = step1.Split(delimiterChars); // Get words
string[] step2b = s.Split(delimiterChars); // Get words
string sFinal = "";
for (int i = 0; i < step2a.Count()-1; i++) // copy count-1 words
{
if (i == 0)
{
sFinal = step2a[i];
}
else
{
sFinal = sFinal + " " + step2a[i];
}
}
// Check if last word is a complete word.
if (step2a[step2a.Count() - 1] == step2b[step2a.Count() - 1])
{
sFinal = sFinal + " " + step2b[step2a.Count() - 1] + ".";
}
else
{
sFinal = sFinal + ".";
}