Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 正则表达式:使用限制限定符访问嵌套匹配_Regex_String_Replace - Fatal编程技术网

Regex 正则表达式:使用限制限定符访问嵌套匹配

Regex 正则表达式:使用限制限定符访问嵌套匹配,regex,string,replace,Regex,String,Replace,所以我的正则表达式是: ((('.*'),(\n)){2}) 我的主题是 'Welcome', 'to', 'RegExr', 'to', 'sad', 所以我想 'Welcome','to', 'RegExr','to', 'sad', 我该怎么做?如果我只写$2,它会先给我'to''sad',而不是'Welcome''to''RegExr''to''sad';第二(我认为最重要的)我如何访问{2}这些主题?两行收缩场景 你可以用 \n(.*(?:\n|$)) 并替换为$1。如果LF前

所以我的正则表达式是:

((('.*'),(\n)){2})
我的主题是

'Welcome',
'to',
'RegExr',
'to',
'sad',
所以我想

'Welcome','to',
'RegExr','to',
'sad',
我该怎么做?如果我只写
$2
,它会先给我
'to''sad'
,而不是
'Welcome''to''RegExr''to''sad'
;第二(我认为最重要的)我如何访问
{2}
这些主题?

两行收缩场景 你可以用

\n(.*(?:\n|$))
并替换为
$1
。如果LF前有CR,则使用

\r?\n(.*(?:\r?\n|$))
其中
\r?\n
匹配可选的CR abd,然后是LF。请注意,为了匹配主要的三种换行符类型,您可以将
\r?\n
替换为
(?:\r\n?|\n)
。或者,如果支持
\R
(任何换行符)构造:

\R(.*(?:\R|$))

详细信息

  • \n
    -换行符
  • (.*)
    -第1组捕获除换行符(
    *
    )之外的任何0+字符,直到并包括换行符或字符串结尾(
    $
收缩任意行数 您可以使用正则表达式匹配5行:

然后在匹配计算器/回调函数(方法)中删除所有换行符

见a:

输出:

'text 1','text 2','text 3','text 4','text 5',
'text 6','text 7','text 8','text 9','text 10',
'MORE here'

这里最重要的问题是,您使用的是哪个正则表达式引擎?此外,请提供更多关于您的任务的上下文。你的思考方式可能不是唯一的思考方式。好吧,但如果我有两个以上的?5,10,15-不要紧?同样的例子,但是(('.''),(\n)){5
或10或15
}@Nikita_kharkov_ua:仅仅用一个正则表达式是没有办法做到的。什么是编程语言?请参阅我的更新,场景2。非常感谢您提供完整的答案!:)
$s = "'text 1',\n'text 2',\n'text 3',\n'text 4',\n'text 5',\n'text 6',\n'text 7',\n'text 8',\n'text 9',\n'text 10',\n'MORE here'\n";
$lines_to_shrink = 5;
echo preg_replace_callback("~'.*',(?:\R'.*',){" . ($lines_to_shrink-1) . "}~", function($m) {
    return str_replace(array("\n", "\r"), "", $m[0]);
}, $s);
'text 1','text 2','text 3','text 4','text 5',
'text 6','text 7','text 8','text 9','text 10',
'MORE here'