Разделить по разделителю, не удаляя его из строки

Я хочу использовать регулярное выражение для разделения длинной строки на отдельные строки. Строка может включать любой возможный символ Юникода. Строка «заканчивается» точкой («.» - одна или несколько) или новой строкой («\ n»).

Пример:

Эта строка будет входом:

"line1. line2.. line3... line4.... line5..... line6
\n
line7"

Выход:

  • "линия 1."
  • "строка2 .."
  • "строка3 ..."
  • "строка4 ...."
  • "line5 ....."
  • "строка6"
  • "line7"

person No1Lives4Ever    schedule 12.05.2014    source источник
comment
В вашем примере похоже, что вы просто хотите разделить на пробелы? например inputString.Split (новый char [] {'', '\ r', '\ n', '\ t'}, StringSplitOptions.RemoveEmptyEntries)   -  person Chris Phillips    schedule 12.05.2014


Ответы (3)


Если я понимаю, о чем вы просите, вы можете попробовать такой шаблон:

(?<=\.)(?!\.)|\n

Это разделит строку в любой позиции, которой предшествует ., но не следует . или символ \n.

Обратите внимание, что этот шаблон сохраняет любые пробелы после точек, например:

var input = @"line1. line2.. line3... line4.... line5..... line6\nline7";
var output = Regex.Split(input, @"(?<=\.)(?!\.)|\n");

Производит

line1. 
 line2.. 
 line3... 
 line4.... 
 line5..... 
 line6 
line7 

Если вы хотите избавиться от пробелов, просто измените это на:

(?<=\.)(?!\.)\s*|\n

Но если вы знаете, что за точками всегда следует пробел, вы можете упростить это до:

(?<=\.)\s+|\n
person p.s.w.g    schedule 12.05.2014

Попробуй это:

String result = Regex.Replace(subject, @"""?(\w+([.]+)?)(?:[\n ]|[""\n]$)+", @"""$1""\n");

/*
"line1."
"line2.."
"line3..."
"line4...."
"line5....."
"line6"
"line7"
*/

Объяснение регулярного выражения

"?(\w+([.]+)?)(?:[\n ]|["\n]$)+

Match the character “"” literally «"?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the regular expression below and capture its match into backreference number 1 «(\w+([.]+)?)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match the regular expression below and capture its match into backreference number 2 «([.]+)?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Match the character “.” «[.]+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below «(?:[\n ]|["\n]$)+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match either the regular expression below (attempting the next alternative only if this one fails) «[\n ]»
      Match a single character present in the list below «[\n ]»
         A line feed character «\n»
         The character “ ” « »
   Or match regular expression number 2 below (the entire group fails if this one fails to match) «["\n]$»
      Match a single character present in the list below «["\n]»
         The character “"” «"»
         A line feed character «\n»
      Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
person Pedro Lobito    schedule 12.05.2014

Если вы хотите, чтобы все точки оставались нетронутыми, а за точками следовало пустое пространство, тогда это может быть ваше регулярное выражение:

String result = Regex.Replace(t, @".\s", @".\n");

Это будет одна строка. Вы не указали, хотите ли вы больше строк или одну в качестве результата.

person Dávid Kaya    schedule 12.05.2014