开发者

Term with no alphanumeric characters before or after

I am trying to write a regular expression that matches all occurrences of a specified word, but must not have any alphanumeric characters prefixed or suffixed.

For example, searching for the term开发者_开发问答 "cat" should not return terms like "catalyst".

Here is what I have so far:

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

This should return the word "TERMPLACEHOLDER" on its own.

Any ideas?

Thanks.


How about:

\bTERMPLACEHOLDER\b


You could use word boundaries: \bTERMPLACEHOLDER\b

A quick test in Javascript:

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

console.log(a.match(/\bcat\b/));

Returns just "cat".


You may be looking for word boundaries. From there, you can use wildcards like \w*? on either side of the word if you want to make it match partials

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


Be carefull When you say "word" refering to a substring you want to find. On the regulare expression side "word" has a different meaning, its a character class.

Define the 'literal' string you would like to find (not word). This can be anything, sentences, punctuation, newline combinations. Example "find this \exact phrase <> !abc".
Since this is going to be part of a regular expression (not the whole regex), you can escape the special regular expression metacharacters that might be embedded.

string = 'foo.bar'  // the string you want to find
string =~ s/[.*+?|()\[\]{}^\$\\]/\\$&/g  // Escape metachars

Now the 'literal' string is ready to be inserted into the regular expression. Note that if you want to individually allow classes or want metachars in the string, you would have to escape this yourself.

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

Perl sample -

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";
  }

Output -

-->'foo.bar'
foo.bar and !fooAbar and afoo.bar.-->'foo.bar'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜