Reputation: 5832
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
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
Reputation: 27271
How about:
@"^USE \s ( ([^ \[\] ]+) | (\[ [^ \[\] ]+ \]) )$"
The ([^ \[\] ]+)
matches any non-[]
characters; the (\[ [^ \[\] ]+ \])
matches [...]
otherwise.
Upvotes: 0
Reputation: 9332
Not very pretty, but at least this won't capture USE [DBName
or USE DBName]
:
^USE (?=\[\w+\]$|\w+$)\[?(\w+)
Upvotes: 3
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