开发者

Regex Question - Exclude Certain Characters

开发者 https://www.devze.com 2023-03-04 12:28 出处:网络
If I want to exclude /* in regex how would I write it? I 开发者_如何学Chave tried: [^/[*]] ([^/][^*])

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

I 开发者_如何学Chave tried:

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

But to no avail...


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

([^/]|/[^*])+/?


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('^([^/]|/(?!\\*))*$')


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: *


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


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

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

0

精彩评论

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