Split a string after reading square brackets in c# [duplicate] - c#

This question already has answers here:
splitting a string based on multiple char delimiters
(7 answers)
Closed 5 years ago.
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string new = test.Trim("[");
I want output "AccoutNumber".
I have tried the below code but not getting the desired result:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[');
string newvalue = test[1];

Just use Split with two delimiters:
string[] test = "Transaction.Parameters[\"ExpOtherX\"].Caption".Split('[', ']');
string newvalue = test[1];

You can also use Regex:
string test = "Account.Parameters[\"AccountNumber\"].Caption";
var match = System.Text.RegularExpressions.Regex.Match(test, ".*?\\.Parameters\\[\"(.*?)\"]");
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
.*? is a non greedy wildcart capture, so it will match your string until it reaches the next part (in our case, it will stop at .Parameters[", match the string, and then at "])
It will match .Parameters["..."]., and extract the "..." part.

you can do a Split to that string...
string test = "Account.Parameters[\"AccountNumber\"].Caption";
string output = test.Split('[', ']')[1];
Console.WriteLine(output);

Related

Substring in c# to find second part in the string [duplicate]

This question already has answers here:
How can I split a string with a string delimiter? [duplicate]
(7 answers)
Closed 4 years ago.
How to find the second part of the string using substring in c#
I have follwwing string:
string str = "George Micahel R - 412352434";
I wanted the above string as two parts.Before "-" and after "-"
I have my first part using following code:
string firstPart = str.Substring(0,str.IndexOf(" - "));
When I am trying for the second part using the following code it gives me an error.
string secondPart = str.Substring(str.IndexOf(" - "), Len(str);
How to get the second part(only number)?
Thanks in advance.
Simply use split function:
var splittedArray = str.Split('-');
var leftPart = splittedArray[0];
var rightPart = splittedArray[1];
Use the Split() method instead.
string str = "George Micahel R - 412352434";
string[] words = str.Split('-');
Console.WriteLine(words[0].Trim()); # George Micahel R
Console.WriteLine(words[1].Trim()); # 412352434

RegEx in C# Replace Method [duplicate]

This question already has answers here:
C#: How to Delete the matching substring between 2 strings?
(6 answers)
Closed 4 years ago.
I am trying to write the RegEx for replacing "name" part in below string.
\profile\name\details
Where name: -Can have special characters
-No spaces
Let's say I want to replace "name" in above path with ABCD, the result would be
\profile\ABCD\details
What would be the RegEx to be used in Replace for this?
I have tried [a-zA-Z0-9##$%&*+\-_(),+':;?.,!\[\]\s\\/]+$ but it's not working.
As your dynamic part is surrounded by two static part you can use them to find it.
\\profile\\(.*)\\details
Now if you want to replace only the middle part you can either use LookAround.
string pattern = #"(?<=\\profile\\).*(?=\\details)";
string substitution = #"titi";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Or use the replacement patterns $GroupIndex
string pattern = #"(\\profile\\)(.*)(\\details)";
string substitution = #"$1Replacement$3";
string input = #"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
For readable nammed group substitution is a possibility.

Regex replace semicolon between quotation marks C# [duplicate]

This question already has answers here:
How to remove all commas that are inside quotes (") with C# and regex
(3 answers)
Closed 3 years ago.
I want to replace all semicolons that are enclosed in quotation marks with a space. How can I do this in C#?
For example:
this string:
this is an example; "this is other ; example"
Would return:
this is an example; "this is other example"
I await your help!
Edited: This will work.
string yourString = "hello there; \"this should ; be replaced \"";
string fixedString = Regex.Replace(yourString, "(\"[^\",]+);([^\"]+\")", delegate (Match match)
{
string v = match.ToString();
return v.Replace(";", " ");
});
Try following :
string input = "this is an example; \"this is other ; example\"";
string pattern = "\"(?'prefix'[^;]+);(?'suffix'[^\"]+)\"";
string output = Regex.Replace(input,pattern,"\"${prefix} ${suffix}\"");

What is the proper way to split a string by regex [duplicate]

This question already has answers here:
How to keep the delimiters of Regex.Split?
(6 answers)
Closed 6 years ago.
I have a text string with a custom macro:
"Some text {MACRO(parameter1)} more text {MACRO(parameter2)}"
In order to process the macro I want to split the string like that:
expected result
"Some text "
"{MACRO(parameter1)}"
" more text "
"{MACRO(parameter2)}"
I've tried to split the string using Regex.Split()
public static string[] Split(string input)
{
var regex = new Regex(#"{MACRO\((.*)\)}");
var lines = regex.Split(input)
return lines;
}
However Regex.Split() deletes the match itself and gives me the following:
actual result
"Some text "
" more text "
I know I could parse the string doing iterations of .Match() and .Substring()
But is there an easy way get the result along with the matches?
Try this
string input = "Some text {MACRO(parameter1)} more text {MACRO(parameter2)}";
string pattern = #"(?'text'[^\{]+)\{(?'macro'[^\}]+)\}";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("text : '{0}'; macro : '{1}'", match.Groups["text"].Value.Trim(), match.Groups["macro"].Value.Trim());
}
Console.ReadLine();

How to extract number values from string mix with numbers and characters in C#? [duplicate]

This question already has answers here:
How to get number from a string
(5 answers)
Closed 7 years ago.
I am quite new to regular expression. My requirement is to extract number from string that includes mix of numbers and characters. I have tried below codes but I can only get the first number from string.
String serialNumber= "000745 TO 000748,00050-00052"
Match match = Regex.Match(serialNumber), #"(\d)+", RegexOptions.IgnoreCase);
if (match.Success)
{
int a = Convert.ToInt32(match); // This part not sure how to do
}
Expected result is:
000745
000748
00050
00052
string strRegex = #"\d+";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"000745 TO 000748,00050-00052";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
You need to loop through your matches to get all the matches.

Categories