Ahmed ilyas
Ahmed ilyas

Reputation: 5832

Regex - match with optional []?

I am trying to do a pattern match to strip out, from a long SQL Script, anywhere where it has the following:

USE [DBName]
USE DBName

I have the regex for the first one, but what about the second? How would I specify that the [] are optional, but the whole line must match?

Syntax for first:

@"USE \[(.*?)\]"

Upvotes: 0

Views: 156

Answers (4)

Raphael
Raphael

Reputation: 1857

You can use the ? quantifier:

@"USE \[?(\w+)\]?"

It checks if there is zero or one of the preceding expression (also, you forgot to escape "[" and "]").

Upvotes: 0

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

How about:

@"^USE \s ( ([^ \[\] ]+) | (\[ [^ \[\] ]+ \]) )$"

The ([^ \[\] ]+) matches any non-[] characters; the (\[ [^ \[\] ]+ \]) matches [...] otherwise.

Upvotes: 0

Jacob Eggers
Jacob Eggers

Reputation: 9332

Not very pretty, but at least this won't capture USE [DBName or USE DBName]:

^USE (?=\[\w+\]$|\w+$)\[?(\w+)

Upvotes: 3

Paul
Paul

Reputation: 141917

The ? quantifier means 0 or 1:

@"USE \[?(.*?)\]?"

This will also match USE [DBName or USE DBName], but since it is greedy by default it won't be a problem, unless you actually have lines like that in your SQL script (in which case you probably want them stripped anyways :P).

Upvotes: 2

Related Questions