I thought I was doing \[/b\]
bu开发者_运维技巧t the machine disagrees.
How do you match
[ ]
with regex?
\[ \]
should do just fine. At least in the Java regular expression engine.
System.out.println("[ ]".matches("\\[ \\]")); // prints true
Not sure where you get the /b
from. Perhaps you're after a "blank" character. The most common expression for whitespace characters is \s
. I.e., you could do \[\s\]
.
(Matching balanced [
]
is another story though. A task which regular expression are not very well suited for.)
It's hard to answer well without knowing which flavor of regex you're using, but:
If you're writing a regular expression literal in a language (like JavaScript) that has them, then just put a backslash in front of the [
and ]
. E.g.:
var re = /\[\/b\]/;
...creates a regular expression that will match a [
followed by a /
followed by a b
followed by a ]
. (I had to escape the /
because in JavaScript regular expression literals, of course the /
is the delimiter.)
In languages where you use a string to specify the regular expression (Java, for instance), escaping can be confusing, because you have to escape with a backslash, but of course backslashes are special in strings and so you have to escape them. You end up with lots of them:
Pattern p = Pattern.compile("\\[/b\\]");
That creates a regex that does what the one above does, but note how we had to escape the escapes.
'^[a-z]' // Should do fine in UNIX and possibly PERL/PHP too.
Example one with the grep command (similar to find)
grep '^[A-Z].?' file.txt
Find words that begin with a capital letter and then any characters after whether capitals or not.
Hope that helps.
DL.
精彩评论