Remove white space from part of a string - c#

I have the text:
SMS \r\n\t• Map - locations of
How can I remove all of the white space between • and the first following character?
The above example should result in
SMS \r\n\t•Map - locations of

By using a regular expression it can be done like so:
var input = "SMS \r\n\t• Map - locations of";
var regexPattern = #"(?<=•)\s+(?=\w)";
var cleanedInput = Regex.Replace(input, regexPattern, String.Empty);
This will replace any whitespace between • and the first word character with an empty string.

string s = "SMS \r\n\t• Map - locations of";
string[] temp = s.Split('•');
s = temp[0]+temp[1].TrimStart(' ');

You can use this Regex:
string toInsertBetween = string.Empty;
string toReplace = "SMS \r\n\t• Map - locations of";
string res = Regex.Replace(toReplace, "•[ ]+([^ ])", "•" + toInsertBetween + "$1");

Related

C# replace chars between set of chars

if I have:
string newMangerName = "RandomName";
string manager = "CN=Kylie Seany,OU=Test,OU=Users"
So the CN name value will be different for every manager,
I want to replace the CN name value with newManger
e.g
string newManager = manager.replace("afterCN=", replace(newManagerName);
You could use RegEx:
var src = "CN=Kylie Seany,OU=Test,OU=Users";
var res = Regex.Replace(src, "(?<=CN\\=)(.*?)(?=,|$)", "test");
Console.WriteLine(res);
(?<=CN\=) is a lookbehind requiring that the previous characters were CN=
(?=,|$) is a lookahead requiring that the next character is , or the end of the string.
(.*?) is a non-greedy match-all.
It's simple, if format is fixed you can easily use Indexof and Substring string functions:
string newManagerName = "Some Random Name";
string manager = "CN=Kylie Seany,OU=Test,OU=Users";
int index = manager.IndexOf(",OU=");
string newManager = "CN=" + newManagerName + manager.Substring(index);
Console.WriteLine(newManager);

Replacing first part of string by another

I need to replace multiple file names in a folder. Here is one of the files:
Abc.CDE.EFG
I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef".
Any ideas? I found this but it takes out the dot and not sure how to add the "zef".
var input = _FileInfo.ToString();
var output = input.Substring(input.IndexOf(".").Trim())
Since the question is tagged with regex, you can use a regular expression like so:
var input = "abc.def.efg";
var pattern = "^[^\\.]+";
var replacement = "zef";
var rgx = new Regex(pattern);
var output = rgx.Replace(input, replacement);
Source: https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx
You are almost there, try:
string myString = "Abc.CDE.EFG";
//This splits your string into an array with 3 items
//"Abc", "CDE" and "EFG"
var stringArray = myString.Split('.');
//Now modify the first item by changing it to "zef"
stringArray[0] = "zef";
//Then we rebuild the string by joining the array together
//delimiting each group by a period
string newString = string.Join(".", stringArray);
With this solution you can independently access any of the "blocks" just by referencing the array by index.
Fiddle here
Try this:
var input = _FileInfo.ToString();
var output = "zef" + input.Substring(input.IndexOf("."));
If you know the length of the first string , you can replace mentioning number of characters starting from position until the length you want to replace else.
string s = "Abc.CDE.EFG";
string [] n = s.Split('.');
n[0] = "ZEF";
string p = string.Join(".",n);
Console.WriteLine(p);
}

Split string and print the value of string separately in autocad

534-W1A-R1 this is my file name and I want to split it so it prints like
Code=534 Phase=1 Zone=A
in my Autocad file.
The below split code should work:
string str = #"534-W1A-R1";
var split = str.Split('-');
string code = split.First();
string phase = new string(split.ElementAt(1).Skip(1).Take(1).ToArray());
string zone = new string(split.ElementAt(1).Skip(2).Take(1).ToArray());
string result = String.Format("Code={0} Phase={1} Zone={2}", code, phase, zone);
Console.WriteLine(result);
Output:
Code=534 Phase=1 Zone=A
Use the Substring() method.
string input = "534-W1A-R1";
string sub = input.Substring(0, 3);
string sub2 = input.Substring(5, 1);
string sub3 = input.Substring(6, 1);
Console.WriteLine("Code={0} Phase={1} Zone={2}", sub, sub2, sub3);
Output:
Code=534 Phase=1 Zone=A
You have different ways to do it. if you are sure about the format of the text you can just use this:
var str= "534-W1A-R1";
var parts=str.Split('-');
var code= parts[0];
var secondPart= parts[1];
var phase=secondPart.Substring(1,secondPart.Length-2);
var zone=secondPart[secondPart.Length-1];
You can also use Regex if it is more complicated.
Using Regex
Edit: added some comments (pattern description)
var pattern = #"^(\d+)-[A-Z](\d+)([A-Z])-";
/* pattern description:
^(\d+) group 1: one or more digits at the begining
- one hyphen (literal)
[A-Z] one alphabetic character
(\d+) group 2: one or more digits
([A-Z]) group 3: one alphabetic character
- one hyphen (literal)
*/
var input = "534-W1A-R1";
var groups = Regex.Match(input, pattern, RegexOptions.IgnoreCase).Groups;
var code = groups[1].Value;
var phase = groups[2].Value;
var zone = groups[3].Value;

How to replace the text between two characters in c#

I am bit confused writing the regex for finding the Text between the two delimiters { } and replace the text with another text in c#,how to replace?
I tried this.
StreamReader sr = new StreamReader(#"C:abc.txt");
string line;
line = sr.ReadLine();
while (line != null)
{
if (line.StartsWith("<"))
{
if (line.IndexOf('{') == 29)
{
string s = line;
int start = s.IndexOf("{");
int end = s.IndexOf("}");
string result = s.Substring(start+1, end - start - 1);
}
}
//write the lie to console window
Console.Write Line(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
I want replace the found text(result) with another text.
Use Regex with pattern: \{([^\}]+)\}
Regex yourRegex = new Regex(#"\{([^\}]+)\}");
string result = yourRegex.Replace(yourString, "anyReplacement");
string s = "data{value here} data";
int start = s.IndexOf("{");
int end = s.IndexOf("}", start);
string result = s.Substring(start+1, end - start - 1);
s = s.Replace(result, "your replacement value");
To get the string between the parentheses to be replaced, use the Regex pattern
string errString = "This {match here} uses 3 other {match here} to {match here} the {match here}ation";
string toReplace = Regex.Match(errString, #"\{([^\}]+)\}").Groups[1].Value;
Console.WriteLine(toReplace); // prints 'match here'
To then replace the text found you can simply use the Replace method as follows:
string correctString = errString.Replace(toReplace, "document");
Explanation of the Regex pattern:
\{ # Escaped curly parentheses, means "starts with a '{' character"
( # Parentheses in a regex mean "put (capture) the stuff
# in between into the Groups array"
[^}] # Any character that is not a '}' character
* # Zero or more occurrences of the aforementioned "non '}' char"
) # Close the capturing group
\} # "Ends with a '}' character"
The following regular expression will match the criteria you specified:
string pattern = #"^(\<.{27})(\{[^}]*\})(.*)";
The following would perform a replace:
string result = Regex.Replace(input, pattern, "$1 REPLACE $3");
For the input: "<012345678901234567890123456{sdfsdfsdf}sadfsdf" this gives the output "<012345678901234567890123456 REPLACE sadfsdf"
You need two calls to Substring(), rather than one: One to get textBefore, the other to get textAfter, and then you concatenate those with your replacement.
int start = s.IndexOf("{");
int end = s.IndexOf("}");
//I skip the check that end is valid too avoid clutter
string textBefore = s.Substring(0, start);
string textAfter = s.Substring(end+1);
string replacedText = textBefore + newText + textAfter;
If you want to keep the braces, you need a small adjustment:
int start = s.IndexOf("{");
int end = s.IndexOf("}");
string textBefore = s.Substring(0, start-1);
string textAfter = s.Substring(end);
string replacedText = textBefore + newText + textAfter;
the simplest way is to use split method if you want to avoid any regex .. this is an aproach :
string s = "sometext {getthis}";
string result= s.Split(new char[] { '{', '}' })[1];
You can use the Regex expression that some others have already posted, or you can use a more advanced Regex that uses balancing groups to make sure the opening { is balanced by a closing }.
That expression is then (?<BRACE>\{)([^\}]*)(?<-BRACE>\})
You can test this expression online at RegexHero.
You simply match your input string with this Regex pattern, then use the replace methods of Regex, for instance:
var result = Regex.Replace(input, "(?<BRACE>\{)([^\}]*)(?<-BRACE>\})", textToReplaceWith);
For more C# Regex Replace examples, see http://www.dotnetperls.com/regex-replace.

Regular Expression to divide a string with pipe-delimited into multiple groups

I'm writing a c# code that divide a string into two different groups. a string is pipe-delimited as example below:
there could be an empty space between two pipes.
number of pipes to "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w" are fixed; In this case, there are 4 pipes.
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
const string sPattern = #"What should it be here?????";
var regex = new Regex(sPattern);
var match = regex.Match(value);
if (match.Success)
{
var begin = match.Groups["begin"].Value;
var middle = match.Groups["middle"].Value;
var end = match.Groups["end"].Value;
}
I am trying to get the output of the code to return as following:
begin = "122312121|test value||test value 2|"
middle = "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w"
end = "|123456789|123456789"
However, I'm so new to regular expression, and I have tried to write a regular expression for variable sPattern, but could not produce the right regular expression for it. Could any please help? Thanks.
you should use String.Split
string [] sarray = value.Split('|')
What that will do is give you the array
{"122312121", "test value", "" , "test value" , "2", "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w", "123456789", "123456789"}
and 5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w will be in sarray[5]
If you're looking for a regular expression to match this and want to use a regular expression rather than .Split, you could try this:
"^((.*?[|]){4})(.*?)([|].*)*$"
or more explicitly:
"^(?<begin>(.*?[|]){4})(?<middle>.*?)(?<end>[|].*)*$"
This is based on the fact that you said the number of pipes before your long string is fixed (at four).
Your code would then read as follows:
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
const string sPattern = #"^((.*?[|]){4})(.*?)([|].*)*$";
var regex = new Regex(sPattern);
var match = regex.Match(value);
if (match.Success)
{
var begin = match.Groups[1].Value;
var middle = match.Groups[3].Value;
var end = match.Groups[4].Value;
}
The trick may be to escape the pipe character:
const string sPattern = #"(?<begin>[^|]*\|[^|]*\|[^|]*\|[^|]*\|)" +
"(?<middle>[^|]*)" +
"(?<end>\|.*)";
You could use String.Split and some Linq to do what you need
Rough example:
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
string[] split = value.Split('|');
string begin = string.Join("|", split.Take(4));
string middle = split.Skip(4).Take(1).FirstOrDefault();
string end = "|" + string.Join("|", split.Skip(5).Take(2));
Returns
begin = "122312121|test value||test value 2|"
middle = "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w"
end = "|123456789|123456789"
Here's another one:
^(?<begin>(.*?\|){4})(?<middle>.*?(?=\|))(?<end>.*)

Categories

Resources