I am using c# and in code from appsettings.json I take strings and convert them if special chars exists. this is my code
int? a = applicationRequestViewModel.GetApplicantIndex();
int? g = applicationRequestViewModel.GetGurantorIndex();
foreach (var keys in _options.Value.RegisterParamKeys)
{
string value = keys.Split(";")[0];
string name = keys.Split(";")[1];
string key = value.Split(":")[typeOfApplicant];
key = Regex.Replace(key, #"[^\[a\]]", "[" + a + "]");
key = Regex.Replace(key, #"[^\[g\]]", "[" + g + "]");
var registrationProperty = new RegistrationProperty() { };
registrationProperty.Name = name;
registrationProperty.Value = (string)rss.SelectToken(key);
listOfRegistrationProperty.Add(registrationProperty);
}
from appsettings.json I took below strings
"RegisterBatchParams": [
"applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber;applicationNumber",
"applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType;applicantType",
"applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment;customerSegment",
"applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText;applicationStatus",
"applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName;customerName"
],
for the last string I want to change "applicants[a]" to with index number but it doesn't convert as expected how can I convert correctly?
As expected result
applicationRequestViewModel.applicants[0].businessPartner.person.firstName
but given result
a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0]a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0][0]
Instead of #"[^\[a\]]" use #"\[a\]".
But you don't even need regex for this. Simple string.Replace will do the job just as well.
Or, you can try this regex and replace only char inside of parentheses.
[a](?=[]])
Related
I have a string Classic-T50 (Black+Grey)
when i send to by query string it will show in next page
Classic-T50 (Black Grey)
so i want to add + in space in this string only within bracket() only portion.
Classic-T50 (Black+Grey).
I have tried string.Replace(" ","+").But it produce
Classic-T50+(Black+Grey).
But i want string Classic-T50 (Black+Grey).
Help me please.
You can use a regular expression for replacing all spaces inside brackets:
var pattern = #"\s(?![^)]*\()";
var data = "Classic-T50 (Black Grey)";
var replacement = "+";
var regex = new Regex(pattern);
var transformedData = regex.Replace(data, replacement); // Classic-T50 (Black+Grey)
This approach will work for any input string. E.g., the string Caption ( A B C D ) will transform to Caption (+A+B+C+D+).
Additional links:
Regex explanation: https://regex101.com/r/aN8fV2/1
MSDN: Regex.Replace Method (String, String)
What is the format of the strings that you want to modify? Will this code work?
void Main()
{
var str = "Classic-T50 (Black Grey)";
Console.WriteLine(FormatWithPlus(str));
}
public string FormatWithPlus(string str){
var str1 = str.Substring(0, str.IndexOf('('));
var str2 = str.Substring(str.IndexOf('('));
return str1 + str2.Replace(' ', '+');
}
Use a StringBuilder and convert back to string. StringBuilder's differ from strings in that they're mutable and noninterned. It stores data in an array, and so you can replace characters like you would in an array:
void Main()
{
var input = "Classic-T50 (Black Grey)";
StringBuilder inputsb = new StringBuilder(input);
var openParens = input.IndexOf('(');
var closeParens = input.IndexOf(')');
var count = closeParens - openParens;
//Console.WriteLine(input);
//inputsb[18] = '+';
inputsb.Replace(' ', '+', openParens, count);
Console.WriteLine(inputsb.ToString());
}
See StringBuilder.Replace Method (Char, Char, Int32, Int32
try:
String.Replace("k ","k+")
use this code
public class Program
{
private static void Main(string[] args)
{
const string abc = "Classic-T50 (Black Grey)";
var a = abc.Replace("k ", "k+");
Console.WriteLine(a);
Console.ReadKey();
}
}
You can UrlEncode it to preserve the special character:
Server.UrlEncode(mystring)
Or replace + sign with "%252b" and then encode it:
string myTitle = mystring.Trim().Replace("+", "%252b");
Response.Redirect("~/default.aspx?title=" + Server.UrlEncode(myTitle));
Remember to decode it once you try to retrieve it :
Server.UrlDecode(Request.QueryString["title"]);
I have the value 4,59,999/-. My code is
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", " ");
textBox2.Text= value;
}
Output is: 4 59 999, I need it to be 459999 (without "," , "/" , "-" and " ").
How about without regex?
var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray();
or shorter
var array = s.Where(char.IsDigit).ToArray();
And you can use this array in a string(Char[]) constructor.
var result = new string(array); // 459999
You don't need regex, you could use:
textBox2.Text = String.Concat(s.Where(Char.IsDigit));
Much better is to use decimal.Parse/TryParse:
string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
textBox2.Text = price.ToString("G");
Just replace with empty string.
string value = Regex.Replace(s, #"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;
Note You don't require the if as the regex replace will work only if there is a match for non digits ([^\d])
Should just be a case of replacing it with an empty string instead of a space?
Regex.Replace(s, #"[^\d]", String.Empty);
Currently you're replacing these characters with a space. Use an empty set of quotes instead.
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", "");
textBox2.Text= value;
}
You are replacing the ",", "/", "-" and " " with a white space. Try this instead:
string value = Regex.Replace(s, #"[^\d]", "");
Hope this helps.
Linq is a possible solution:
String s = "4,59,999/-";
...
textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());
Try something like this it will work 100% in php so just change some syntax for C#
<?php
$str = "4,59,999/-.";
echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>
I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.
Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!
if (fileNameArrayEdited.StartsWith("\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
// Put all file names in root directory into array.
string[] fileNameArray = Directory.GetFiles(#specifiedDir);
int specifiedDirCount = specifiedDir.Count();
string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
Console.ReadLine();
Use '#' at the beginning of your string if you are searching for exactly two slash
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
But I suspect in here your one slash is escape character
"\\windows"
So you must search for one slash like this:
if (fileNameArrayEdited.StartsWith(#"\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
When we write
string s1 = "\\" ;
// actual value stored in s1 is "\"
string s2 = #"\\" ;
// actual value stored in s2 is "\\"
The second type of string(s) are called "verbatim" strings.
I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}
How can I strip a suffix from a string, and return it, using C#/LINQ? Example:
string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };
string myString = "DeleteItemMessagePlural";
string stringWithoutSuffix = myString.???; // what do I do here?
// stringWithoutSuffix == "DeleteItemMessage"
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));
You need to build a regular expression from the list:
var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");
string stringWithoutSuffix = regex.Replace(myString, "");
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));
// Replace the matching one:
var stringWithoutSuffix = Regex.Replace(myString, "(" +suffixToStrip + ")$", "");
OR, since you know the length of the matching suffix:
// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;
// Remove the matching one:
var stringWithoutSuffix = myString.Substring(0, myString.Length - trim);