4

If I want to exclude /* in regex how would I write it?

I have tried:

[^/[*]]
([^/][^*])

But to no avail...

user559142
  • 12,279
  • 49
  • 116
  • 179

5 Answers5

3

You must match not /, OR / followed by not *:

([^/]|/[^*])+/?
orlp
  • 112,504
  • 36
  • 218
  • 315
2

Use a negative lookahead to check that, if the input contains /, it does not contain / followed by /*. In JavaScript, x not followed by y would be x(?!y), so:

  • Either the input contains no /: new RegExp('^[^/]*$'), or
  • Any / found must not be followed by *: new RegExp('^/(?!\\*)$') (note, the * must be escaped with a \\ since * is a special character.

To combine the two expressions:

new RegExp('^([^/]|/(?!\\*))*$')
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I was trying this, it doesn't work... all it does it capture standalone `/` characters, it doesn't get anything else. From the question it sounds like he wants everything except those. – eykanal May 09 '11 at 14:07
0

In Java following Pattern should work for you:

Pattern pt = Pattern.compile("((?<!/)[*])");

Which means match * which is NOT preceded by /.

TEST CODE

String str = "Hello /* World";
Pattern pt = Pattern.compile("((?<!/)[*])");
Matcher m = pt.matcher(str);
if (m.find()) {
    System.out.println("Matched1: " + m.group(0));
}
String str1 = "Hello * World";
m = pt.matcher(str1);
if (m.find()) {
    System.out.println("Matched2: " + m.group(0));
}

OUTPUT

Matched2: *
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Can't you just deny a positive match? So the kernel is just "/*", but the * needs masking by backslash, which needs masking itself, and the pattern might be followed or preceded by something, so .* before and after the /\\* is needed: ".*/\\*.*".

val samples = List ("*no", "/*yes", "yes/*yes", "yes/*", "no/", "yes/*yes/*yes", "n/o*")  
samples: List[java.lang.String] = List(*no, /*yes, yes/*yes, yes/*, no/, yes/*yes/*yes, n/o*)

scala> samples.foreach (s => println (s + "\t" + (! s.matches (".*/\\*.*"))))                   
*no true
/*yes   false
yes/*yes    false
yes/*   false
no/ true
yes/*yes/*yes   false
n/o*    true
user unknown
  • 35,537
  • 11
  • 75
  • 121
-1

See http://mindprod.com/jgloss/regex.html#EXCLUSION

e.g. [^"] or [^w-z] for anything but quote and anything but wxyz

user1332994
  • 100
  • 1
  • 1