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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.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 - Fatal编程技术网

Regex 组合不同的表达

Regex 组合不同的表达,regex,Regex,我对正则表达式还是新手,希望将不同的表达式组合在一起。现在所有这些表达式单独使用时都可以工作,但我似乎无法将它们组合成一个工作字符串 我只想匹配开头有1%且后面没有空格的字符串 范例 %string => Match % string => No Match %%string => No Match 现在我有这些表达: (^[^%]*%[^%]*$) - Matches only one % but with whitespace (%\S+)([^\n]+) - Mat

我对正则表达式还是新手,希望将不同的表达式组合在一起。现在所有这些表达式单独使用时都可以工作,但我似乎无法将它们组合成一个工作字符串

我只想匹配开头有1%且后面没有空格的字符串

范例

%string  => Match
% string => No Match
%%string => No Match
现在我有这些表达:

(^[^%]*%[^%]*$) - Matches only one % but with whitespace
(%\S+)([^\n]+)  - Matches strings with the % and no whitespace behind but also matches the %% string that shouldn't be matched
我试着把它们和一个接一个的复制结合起来

(^[^%]*%[^%]*$)(\S+)([^\n]+)
但那是行不通的。我知道在组合它们时我做错了什么,我只是不知道是什么。

您可以使用

^%[^\s%]*$

详细信息

  • ^
    -字符串锚的开始
  • %
    -百分比符号
  • [^\s%]*
    -与零个或多个字符(除空格和
    %
  • $
    -字符串结束锚定

这要简单得多。谢谢我还想匹配整个字符串,即使它与整行的空格分隔。例如“%string”。我尝试了这个组([^\n]+),它匹配整行中的所有内容。当我现在添加它时,它不起作用,我将它放在第二个组中,该组与您的解决方案匹配。这是否意味着您不希望只允许空白作为第二个符号?嗯,这使得要求有点不明确。试试
^%[^\s%][^%]*$
。如果您还需要匹配一个仅由
%
组成的字符串,那么您需要一个向前看-
^%(?!\s)[^%]*$
确切地说!这很有效。再次感谢你!我会看一看角色课,这样我就可以自己学习了。