C# How do i get the Right(String) based on one character? - c#

I have this:
MyString = #"C:\\Somepath\otherpath\etc\string";
And i need this string (which can be longer than a group of characters)
How can i do something like:
NewString = MyString.Right(string, when last "\" is found) ?

For a path specifically, you can use Path.GetFileName(String).
var MyString = #"C:\Somepath\otherpath\etc\string";
var NewString = Path.GetFileName(MyString);
Despite the name of the method, it also works on directory names, provided they aren't followed by a trailing backslash. So C:\directory becomes directory, but C:\directory\ becomes the empty string. (This might be what you want, based on how you phrased the question.)

Depending on your environment, you might be able to use the new indices and range features that came with C# 8.0
var result = MyString.Split('\\')[^1];
Indices and Ranges

This will return everything after the last instance of the character '\'.
var result = MyString.Substring(MyString.LastIndexOf('\\') + 1);

If you don't mind using a bit of LINQ:
var result = MyString?.Split('\\').LastOrDefault();

Related

Erase all numbers after a underscore

I have this code which should erase all the numbers after a certain _
var fileNameOnly1 = Regex.Replace(fileNameOnly, #"[_\d]", string.Empty);
I.e.
Input
4a_32
abcdef43252_43242
Current Output
4a2
abcdef432523242
Expected output
4a
abcdef43252
I also tried using #"[_\d]"
is there any way to erase numbers after _ and erase the '_' also ??
You dont specifically mention that you need to use regex and in most cases I would advise against it as regex is rather slow (comparison to other methods) and cumbersome (difficult to read and write).
I would think that it would be better to do this using string manipulation instead.
var fileNameOnly1 = fileNameOnly.Split('_')[0];
The above code will find the first '_' and take all characters before it (returned as a string).
Try this
Pattern
_\d+
Example
var fileNameOnly = "asdads_234asd";
var result = Regex.Replace(fileNameOnly, #"_\d+", string.Empty);
Console.WriteLine(result);
Output
asdadsasd
Simply use this regex:
_\d+
Regex.Replace(fileNameOnly, #"_\d+", string.Empty);

Check array for string that starts with given one (ignoring case)

I am trying to see if my string starts with a string in an array of strings I've created. Here is my code:
string x = "Table a";
string y = "a table";
string[] arr = new string["table", "chair", "plate"]
if (arr.Contains(x.ToLower())){
// this should be true
}
if (arr.Contains(y.ToLower())){
// this should be false
}
How can I make it so my if statement comes up true? Id like to just match the beginning of string x to the contents of the array while ignoring the case and the following characters. I thought I needed regex to do this but I could be mistaken. I'm a bit of a newbie with regex.
It seems you want to check if your string contains an element from your list, so this should be what you are looking for:
if (arr.Any(c => x.ToLower().Contains(c)))
Or simpler:
if (arr.Any(x.ToLower().Contains))
Or based on your comments you may use this:
if (arr.Any(x.ToLower().Split(' ')[0].Contains))
Because you said you want regex...
you can set a regex to var regex = new Regex("(table|plate|fork)");
and check for if(regex.IsMatch(myString)) { ... }
but it for the issue at hand, you dont have to use Regex, as you are searching for an exact substring... you can use
(as #S.Akbari mentioned : if (arr.Any(c => x.ToLower().Contains(c))) { ... }
Enumerable.Contains matches exact values (and there is no build in compare that checks for "starts with"), you need Any that takes predicate that takes each array element as parameter and perform the check. So first step is you want "contains" to be other way around - given string to contain element from array like:
var myString = "some string"
if (arr.Any(arrayItem => myString.Contains(arrayItem)))...
Now you actually asking for "string starts with given word" and not just contains - so you obviously need StartsWith (which conveniently allows to specify case sensitivity unlike Contains - Case insensitive 'Contains(string)'):
if (arr.Any(arrayItem => myString.StartsWith(
arrayItem, StringComparison.CurrentCultureIgnoreCase))) ...
Note that this code will accept "tableAAA bob" - if you really need to break on word boundary regular expression may be better choice. Building regular expressions dynamically is trivial as long as you properly escape all the values.
Regex should be
beginning of string - ^
properly escaped word you are searching for - Escape Special Character in Regex
word break - \b
if (arr.Any(arrayItem => Regex.Match(myString,
String.Format(#"^{0}\b", Regex.Escape(arrayItem)),
RegexOptions.IgnoreCase)) ...
you can do something like below using TypeScript. Instead of Starts with you can also use contains or equals etc..
public namesList: Array<string> = ['name1','name2','name3','name4','name5'];
// SomeString = 'name1, Hello there';
private isNamePresent(SomeString : string):boolean{
if (this.namesList.find(name => SomeString.startsWith(name)))
return true;
return false;
}
I think I understand what you are trying to say here, although there are still some ambiguity. Are you trying to see if 1 word in your String (which is a sentence) exists in your array?
#Amy is correct, this might not have to do with Regex at all.
I think this segment of code will do what you want in Java (which can easily be translated to C#):
Java:
x = x.ToLower();
string[] words = x.Split("\\s+");
foreach(string word in words){
foreach(string element in arr){
if(element.Equals(word)){
return true;
}
}
}
return false;
You can also use a Set to store the elements in your array, which can make look up more efficient.
Java:
x = x.ToLower();
string[] words = x.Split("\\s+");
HashSet<string> set = new HashSet<string>(arr);
for(string word : words){
if(set.contains(word)){
return true;
}
}
return false;
Edit: (12/22, 11:05am)
I rewrote my solution in C#, thanks to reminders by #Amy and #JohnyL. Since the author only wants to match the first word of the string, this edited code should work :)
C#:
static bool contains(){
x = x.ToLower();
string[] words = x.Split(" ");
var set = new HashSet<string>(arr);
if(set.Contains(words[0])){
return true;
}
return false;
}
Sorry my question was so vague but here is the solution thanks to some help from a few people that answered.
var regex = new Regex("^(table|chair|plate) *.*");
if (regex.IsMatch(x.ToLower())){}

Exclude first and last quotation of string in regex result

I'm running a little c# program where I need to extract the escape-quoted words from a string.
Sample code from linqpad:
string s = "action = 0;\r\ndir = \"C:\\\\folder\\\\\";\r\nresult";
var pattern = "\".*?\"";
var result = Regex.Split(s, pattern);
result.Dump();
Input (actual input contains many more escaped even-number-of quotes):
"action = 0;\r\ndir = \"C:\\\\folder\\\\\";\r\nresult"
expected result
"C:\\folder\\"
actual result (2 items)
"action = 0;
dir = "
_____
";
result"
I get exactly the opposite of what I require. How can I make the regex ignore the starting (and ending) quote of the actual string? Why does it include them in the search? I've used the regex from similar SO questions but still don't get the intended result. I only want to filter by escape quotes.
Instead of using Regex.Split, try Regex.Match.
You don't need RegEx. Simply use String.Split(';') and the second array element will have the path you need. You can then Trim() it to get rid of the quotes and Remove() to get rid of the ndir part. Something like:
result = s.Split(';')[1].Trim("\r ".ToCharArray()).Remove(0, 7).Trim('"');

I need to get a string between two strings using regex in C#

I have a string for example: "GamerTag":"A Talented Boy","GamerTileUrl" and what I have been trying and failing to get is the value: A Talented Boy. I need help creating a regex string to get specifically just A Talented Boy. Can somebody please help me!
var str = "\"GamerTag\":\"A Talented Boy\",\"GamerTileUrl\"";
var colonParts = str.Split(':');
if (colonParts.Length >= 2) {
var commaParts = colonParts[1].Split(',');
var aTalentedBoy = commaParts[0];
var gamerTileUrl = commaParts[1];
}
This allows you to also get other parts of the comma-separated list.
Suppose s is your string (no check here):
s = s.Split(':')[1].Split(',')[0].Trim('"');
If you want to have a Regex solution, here it is:
s = "\"GamerTag\":\"A Talented Boy\",\"GamerTileUrl\"";
Regex reg = new Regex("(?<=:\").+?(?=\")");
s = reg.Match(s).Value;
You can use string methods:
string result = text.Split(':').Last().Split(',').First().Trim('"');
The First/Last extension methods prevent exceptions when the separators are missing.
Demo
I think it's safe to assume that your string is actually bigger than what you showed us and it contains multiple key/value pairs? I think this is will do what you are looking for:
str.Split("GamerTag:\"")[1].Split("\"")[1];
The first split targets "GamerTag:" and gets everything after it. The second split gets everything between first and second " that exists in that chunk after "GamerTag:"
How about this?
\:\"([^\"]+)\"
This matches the semicolon and the opening quote, and matches any non-quote characters until the next quote.

C# stripping out the string needed

Ok so i have these strings
location = "C:\\Users\\John\\Desktop\\399";
location = "C:\\Users\\John\\Desktop\\399\\DISK1";
location = "C:\\Users\\John\\Desktop\\399\\DISK2";
location = "\\somewhere\\on\\Network\\399\\DISK2";
how do i strip out the 399 from all these situations ....FYI the number might be 2 digits like 42 so i cant grab the last 3 in the first case....i was thinking of some regex that would take out the DISKn if it exists and grab the number till the \ before the number but i dont know how to do that in C#...any ideas
Here is how to do this with Regex against your example input:
Regex rgx = new Regex("\\\d+");
string result = rgx.Replace(input, string.Empty);
The regular expression will match on a \ followed by at least one digit and replace them. You need to be careful though, as it will not preserve the string if you have this pattern elsewhere in the string.
If your inputs are exactly as you have described, using string.Split can be much more efficient (assuming the portion you need to remove is always last of before last).
Update:
The regex I provided will work only if you have a single part of the path that starts with numbers, not multiples or paths that have begin with numbers but do not end with them.
The information you have provided is not enough to built a regular expression that will do as you wish - how do you distinguish between numeric paths that do need to be stripped out and those that do not, for example?
var parts = location.Split('\\');
var number = parts.Last().Starts("DISK") ? parts[parts.Length - 2] : parts[parts.Length - 1];
strip number out:
var index = parts.Last().Starts("DISK") ? parts.Length - 2 : parts.Length - 1;
var newParts = parts.Take(index).Concat(parts.Skip(index + 1)).ToArray();
var newLocation = string.Join("\\", newParts);
Take a look at the Split() method for breaking the string up around separators. Then you can use techniques such as checking for the last part starting with DISK, or checking for a part that is purely integer (possibly risky, in case higher subdirectories are pure numbers - unless you work from the back!).
int i = int.Parse(location.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries)[4]);

Categories

Resources