[英]Regex Question - Exclude Certain Characters
If I want to exclude /* in regex how would I write it? 如果我想在正则表达式中排除/ *我将如何编写它?
I have tried: 我试过了:
[^/[*]]
([^/][^*])
But to no avail... 但无济于事......
您必须not /
匹配not /
,或/ 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: 在JavaScript中 ,
x
后面没有y
将是x(?!y)
,所以:
/
: new RegExp('^[^/]*$')
, or /
: new RegExp('^[^/]*$')
或 /
found must not be followed by *
: new RegExp('^/(?!\\\\*)$')
(note, the *
must be escaped with a \\\\
since *
is a special character. /
找不到后跟*
: new RegExp('^/(?!\\\\*)$')
(注意, *
必须用\\\\
转义,因为*
是一个特殊字符。 To combine the two expressions: 要结合这两个表达式:
new RegExp('^([^/]|/(?!\\*))*$')
In Java following Pattern should work for you: 在Java中,下面的Pattern应该适合你:
Pattern pt = Pattern.compile("((?<!/)[*])");
Which means match *
which is NOT preceded by /
. 这意味着匹配
*
前面没有/
。
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));
}
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 请参见http://mindprod.com/jgloss/regex.html#EXCLUSION
eg [^"] or [^wz] for anything but quote and anything but wxyz 例如[^“]或[^ wz]除了报价和除了wxyz以外的任何东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.