cjm2671
cjm2671

Reputation: 19486

How do you match [ ] with regex?

I thought I was doing \[/b\]

but the machine disagrees.

Upvotes: 0

Views: 96

Answers (3)

Design Loper
Design Loper

Reputation: 1

'^[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.

Upvotes: 0

aioobe
aioobe

Reputation: 421090

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.)

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074979

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.

Upvotes: 0

Related Questions