Thursday, March 22, 2007

Regex: Using named groups in .NET Regular Expressions

When you match a group in a regular expression, you can reference them in the replace expression with the syntax "$1, $2". But, the better way is to give every group a name.

in search -> (?....pattern...)
in replace -> ${name}
\k --> back reference to a named match

Example:
SearchPattern = (?<tag>bold)>(?<text>[\s\S]+?)</\k<tag>>
ChangePattern =
<${tag}><font color=red>${text}</font></${tag}>


Text:
<bold>this text will be red</bold>

Result:
<bold><font color=red>this text will be red</font></bold>

I hope everything is clear in the example :)

Wednesday, March 21, 2007

.NET: Combine array items into a string (deliminated with comma)

So, here is the quick way to achieve it:

ArrayList arr = new ArrayList();
arr.Add("test1");
arr.Add("test2");
arr.Add("test3");

//be sure all elements are string
string str = String.Join(",", (string[]) arr.ToArray(Type.GetType("System.String")));

MessageBox.Show(str); // test1,test2,test3

SQL: Split function that parses comma delimated string

This is a function that I use frequently (also some of my friends). It is a function in Sql server, that parses a comma-deliminated string and returns a table. By returning a table, you can use this in joins. So, here is the function:

create function fn_Split(
@String
nvarchar (4000),
@Delimiter
nvarchar (10)
)
returns @ValueTable
table ([Value] nvarchar(4000))
begin
declare
@NextString nvarchar(4000)
declare @Pos int
declare
@NextPos int
declare
@CommaCheck nvarchar(1)

--Initialize
set @NextString = ''
set @CommaCheck = right(@String,1)

--Check for trailing Comma, if not exists, INSERT
if (@CommaCheck <> @Delimiter )
set @String = @String + @Delimiter

--Get position of first Comma
set @Pos = charindex(@Delimiter,@String)
set @NextPos = 1

--Loop while there is still a comma in the String of levels
while (@pos <> 0)
begin
set
@NextString = substring(@String,1,@Pos - 1)
insert into @ValueTable ( [Value]) Values (@NextString)
set @String = substring(@String,@pos +1,len(@String))
set @NextPos = @Pos
set @pos = charindex(@Delimiter,@String)
end

return
end
go


How do we use it? Like that:
SELECT * FROM ServicesTable inner join dbo.fn_Split(@ServiceFilter, ',') tbl on tbl.[Value] = ServicesTable.Service)

* Here, the @ServiceFilter is something like "abc,xyz,123".