How to remove extra hyphens from string in c#? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string in which spaces are replaced by hyphen i.e '-' if there multiple hyphens then I want to remove all but one from the string. Only hyphens must be removed; not numbers that are consecutive.
Eg: --11- must be -11- and not -1-
Eg: --12- o/p: -12-
Eg: -12-- o/p: -12-
using Linq or a string function in C#.
I have tried it using str = str.Remove(str.Length - 1);, but it only removes one character.

If you just want to collapse multiple consecutive - characters into one, you could easily do this using regex:
string output = Regex.Replace(input, #"\-+", "-");

try
string sample = "--12";
string Reqdoutput = sample.Replace("--", "-");

If you want to replace just the hyphen, you can do one of the things given in the other answers. For removing all double characters, you can do this:
String input = "------hello-----";
int i = 1;
while (i < input.Length)
{
if (input[i] == input[i - 1])
{
input = input.Remove(i, 1);
}
else
{
i++;
}
}
Console.WriteLine(input); // Will give "-helo-"

Why not just do :
yourString = yourString.Replace("--", "-");
Or did I understand the problem wrong ?

Related

string.IndexOf ignoring escape sequences [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to extract the CN of an LDAP DN string.
Here's an example string that illustrates the problem
var dn = #"CN=Firstname Lastname\, Organization,OU=some ou,DC=company,DC=com";
What I want is the position of the first non escaped ',' character, which is at position 32.
var pos = dn.IndexOf(',');
returns the first comma, regardless of escaping or not. Now can I bring IndexOf to skip the escaped comma in the string?
Assuming that \ should be escaped by itself: \\ to put just \ you can implement a simple
finite state machine
private static int IndexOfUnescaped(string source,
char toFind,
char escapement = '\\') {
if (string.IsNullOrEmpty(source))
return -1;
for (int i = 0; i < source.Length; ++i)
if (source[i] == escapement)
i += 1; // <- skip the next (escaped) character
else if (source[i] == toFind)
return i;
return -1;
}
...
var dn = #"CN=Firstname Lastname\, Organization,OU=some ou,DC=company,DC=com";
var pos = IndexOfUnescaped(dn, ',');
You can use Regex:
string s = #"CN=Firstname Lastname\, Organization,OU=some ou,DC=company,DC=com";
Regex regex = new Regex("(?<!\\\\),", RegexOptions.Compiled);
int firstMatch = regex.Matches(s).FirstOrDefault()?.Index ?? -1;
Demo: https://regex101.com/r/Jxco8K/1
It's using a negative lookbehind, so check all commas and look if it's not preceeded by a backslash.
Colleague of mine whipped up this regex. Not entirely the question, but since I wanted the position to then use SubString it also does the trick.
var CnRegex = new Regex(#"([a-zA-Z_]*)=((?:[^\\,}]|\\.)*)");
var match = CnRegex.Match(input);
if (match.Success)
return match.Value;
return null;
I feared it would come down to a Regex, as in Tim's solution, or 'brute force' as with Dmitry's solution.

How can I return a string between two other strings in C#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string for a page source already created. I need to grab a few lines of text from the string. The string I need is between two other strings. These two strings are "keywords": and ", "
How would I search for a string that has a colon after the quotations such as "keywords":
?
Would I use regex?
Thank you.
In your case, regex is too powerful to use it with such a problem. Just use string.IndexOf() and string.Substring(). Get a position of the word, get a position of the closest comma - there is an overload for this in IndexOf that let you specify starting position of searching.
Here is a code snippet, it is more explaining then I could do it in words.
var text = "\"keywords\":some text you want,and a text you do not want";
var searchFor = "\"keywords\":";
int firstIndex = text.IndexOf(searchFor);
int secondIndex = text.IndexOf(",", firstIndex);
var result = text.Substring(firstIndex + searchFor.Length, secondIndex - searchFor.Length);
The following Regex will match everything between "keywords" and ",":
Regex r = new Regex("keywords:(.*),");
Match m = r.Match(yourStringHere);
foreach(Group g in m.Groups) {
// do your work here
}
You can try like this, without using Regex
string str = "This is an example string and my data is here";
string first = "keywords:";
string second = ",";
int Start, End;
if (str.Contains(first) && str.Contains(second))
{
Start = str.IndexOf(first, 0) + first.Length;
End = str.IndexOf(second, Start);
return str.Substring(Start, End - Start);
}
else
{
return "";
}
This ought to work across multiple lines.
string input = #"blah blah blah ""keywords"":this is " + Environment.NewLine + "what you want right?, more blah...";
string pattern = #"""keywords"":(.*),";
Match match = Regex.Match(input, pattern, RegexOptions.Singleline);
if (match.Success)
{
string stuff = match.Groups[1].Value;
}

Match and replace only line breaks in string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to replace line break in string with blank.if string has only line break it should be replace with blank string if string has text along with line breaks it should not be replace with anything.
string test1 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\nTestcompanyAC\r\nRegistration Number: 19871\r\n\r\n\r\nSTATEMENTS\r\n\r\nYear ended 31 December 2013\r\n\r\n"
string test2 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
output: test1 as it is and test2=""
Thanks
string test2 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
if (test2.All(c => c == '\n' || c == '\r'))
test2 = "";
You can use the ^ and $ delimiters to match beginning and ending.
Regex.Replace(test2, #"^[\r\n]*$", String.Empty)
Why would you bother with Regex.
This does what you need:
if (string.IsNullOrWhitespace(string_variable_here))
string_variable_here = "";
If you're just looking for a blank entry.. the above is all you need.
Just a guess, and a somewhat different attempt, but are you looking for a way to trim your string, to remove leading and ending whitespaces?
str = str.Trim();
That should give you
test1 = "TestcompanyAC\r\nRegistration Number: 19871\r\n\r\n\r\nSTATEMENTS\r\n\r\nYear ended 31 December 2013"
test2 = ""

Characters between two exact characters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let me show you what I want to do...
For example, I have this as an input
......1.......1.................
and what I want to do is
.......1111111..................
So I want to fill the space between the two ones with ones...
Also this should be able to be done too:
......11.....1..................
........11111...................
So I want just the inside...
Any C# help you can give?
This can be solved much easier without requiring a regular expression: You just want to "invert" the area of the string delimited by the first and last occurrence of a "1".
Here's an example solution:
string input = "..........1............1...";
int start = input.IndexOf('1');
int end = input.LastIndexOf('1');
char[] content = input.ToCharArray();
for (int i = start; i <= end; i++)
{
content[i] = content[i] == '1' ? '.' : '1'; //invert
}
string output = new string(content);
a regex way:
with multiline mode:
pattern: (?>(?<=^\.*)|\G)1(?=1*(\.))|\G(?<!^)\.(?=\.*(1))
replacement: $1$2
example:
string pattern = #"(?>(?<=^\.*)|\G)1(?=1*(\.))|\G(?<!^)\.(?=\.*(1))";
string input = #"......1.......1.................
......11.....1..................
......11111111..................";
string replacement = "$1$2";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
string result = rgx.Replace(input, replacement);

Regular expression for parsing ::number::sentence:: [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How will a regex for validation (::number::sentence::) such values look like?
::1::some text::
::2::some text's::
::234::some's text's::
You could use String.Split and avoid a regex completely if your string is as simple as this e.g.
var data = "::234::some's text's::".Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(data[0]); // 234
Console.WriteLine(data[1]); // some's text's
If you need to use it for validation you can still use the same logic as above e.g.
public bool Validate(string str)
{
var data = str.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
double n;
return data.Length == 2 && Double.TryParse(data[0], out n) && !String.IsNullOrWhiteSpace(data[1]);
}
...
bool valid = Validate("::234::some's text's::");
Something like:
^::([0-9]+)::((?:(?!::).)*)::$
Example code:
Match match = Regex.Match("::1::some text::", "::([0-9]+)::((?:(?!::).)*)::");
var groups = match.Groups;
string num = groups[1].ToString();
string text = groups[2].ToString();
explanation:
^ Begin of the string
:: 2x ':'
([0-9]+) Match group 1, the 0-9 digits, one or more
:: 2x ':'
((?:(?!::).)*) Match group 2, any one character that isn't ::, zero or more
:: 2x ':'
$ End of the string
The ((?:(?!::).)*) requires a little more explanation... Let's peel it...
( ... ) the first '(' and last ')', match group 2
So now we have:
(?:(?!::).)*
so
(?: ... )* group without name (non capturing group) repeated 0 or more times. Its content will be put in match group 2 because it's in defined inside match group 2
composed of:
(?!::).
where
. is any character
BUT before "capturing" the "any character" make a check: (?!::) that the any character and the next one aren't :: (it's called zero-width negative lookahead)

Categories