Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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,我正在尝试编写一个正则表达式,它匹配指定单词的所有匹配项,但不能有任何字母数字字符作为前缀或后缀 例如,搜索术语“cat”不应返回诸如“catalyst”之类的术语 以下是我到目前为止的情况: "?<!([a-Z0-9])*?TERMPLACEHOLDER?!([a-Z0-9])*?" “?您可以使用单词边界:\b术语占位符\b Javascript中的快速测试: var a = "this cat is not a catalyst"; console.log(a.match(/\b

我正在尝试编写一个正则表达式,它匹配指定单词的所有匹配项,但不能有任何字母数字字符作为前缀或后缀

例如,搜索术语“cat”不应返回诸如“catalyst”之类的术语

以下是我到目前为止的情况:

"?<!([a-Z0-9])*?TERMPLACEHOLDER?!([a-Z0-9])*?"

“?您可以使用单词边界:
\b术语占位符\b

Javascript中的快速测试:

var a = "this cat is not a catalyst";

console.log(a.match(/\bcat\b/));
只返回“cat”。

如何:

\bTERMPLACEHOLDER\b
您可能正在查找。从那里,您可以在单词的任意一侧使用通配符,如
\w*?
,以使其与部分匹配

Search for any word containing "MYWORD"
\b\w*?MYWORD\w*?\b

Search for any word ending in "ING"
\b\w*?ING\b

Search for any word starting with "TH"
\bTH\w*?\b
当你说“word”时要小心,它指的是你想找到的子字符串。在通常的表达方面,“word”有不同的含义,它是一个字符类

定义要查找的“文字”字符串(不是word)。可以是任何内容、句子、标点符号、换行符组合。例如“查找此\确切的短语!”!abc.“
因为这将是正则表达式(而不是整个正则表达式)的一部分,所以可以避开可能嵌入的特殊正则表达式元字符

string = 'foo.bar'  // the string you want to find
string =~ s/[.*+?|()\[\]{}^\$\\]/\\$&/g  // Escape metachars
现在,可以将“literal”字符串插入到正则表达式中了。请注意,如果您想在字符串中单独允许类或元字符,您必须自己转义

sample =~ /(?<![^\W_])$string(?![^\W_])/ig  // Find the string globally
(expanded)
/ 
  (?<![^\W_])    # assertion: No alphanumeric character behind us
  $string        # the 'string' we want to find
  (?![^\W_])     # assertion: No alphanumeric character in front of us
/ig

您可能应该使用[a-zA-Z0-9]。我认为a-Z不会具有所需的行为。^将否定字符列表。因此,您可能需要尝试类似“/[^a-zA-Z0-9](术语占位符)[^a-zA-Z0-9]/”的内容
use strict;
use warnings;

my $string = 'foo.bar';
my $sample = 'foo.bar and !fooAbar and afoo.bar.foo.bar';

# Quote string metacharacters

  $string =~ s/[.*+?|()\[\]{}^\$\\]/\\$&/g;

# Globally find the string in the sample target

  while ( $sample =~ /(?<![^\W_])$string(?![^\W_])/ig )
  {
      print substr($sample, 0, $-[0]), "-->'",
            substr($sample, $-[0], $+[0] - $-[0]), "'\n";
  }
-->'foo.bar'
foo.bar and !fooAbar and afoo.bar.-->'foo.bar'