简体   繁体   中英

C# string manipulation handling white space with \r\n inbetween

I am trying to find a statement that can match any number of white spaces that may or may not have a line break in between as well

Example of string:

value   \r\n         item

I am trying to use IndexOf() on a string to get the index of the word "value" followed by the word "item" it must match value followed by item because both is used in different context as well.

This is my statement so far:

length = (allItems.IndexOf("value (some white space) item") + "value (some white space) item".Length) - startIndex;

Hope it makes sense and thanks in advance.

This can be done easily with regular expressions:

Regex.Matches("value     \r\n    item", @"value(\s)*item")

You specified "any number of whitespaces", but I suspect you might mean "at least one whitespace" (IE excluding "valueitem" ), in which case you should use @"value(\\s)+item" as your pattern (using a + instead of a * ).

This gets you the index:

string s = "value   \r\n    item";     
string pattern = @"value\s+item";
if (System.Text.RegularExpressions.Regex.IsMatch(s, pattern)) {
    System.Console.WriteLine(s.IndexOf("item"));
}

Thank to the patterns provided by @Rik and @Tom Fenech I could find a way around the problem by using:

   string pattern = "\\s+";
   string replacement = " ";
   Regex rgx = new Regex(pattern);
   string test = rgx.Replace(str, replacement);

To remove all the redundant white space from the string (but still leaving at least one space) and:

    test = test.Replace("\r\n", String.Empty);

To remove the line breaks that was unnecessary. I could then match "value item" and get the index.

Thanks for the answers guys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM