'C#'에 해당되는 글 6건

  1. 2009.04.30 DataTable DataSet DataView Method
  2. 2009.03.03 정규식을 이용한 숫자입력 체크 함수
  3. 2009.02.16 SQL Server 2005 Database Backup and Restore using C# and .NET 2.0
  4. 2009.02.08 c# 정규 표현식
  5. 2009.02.08 C# Regular Expressions
  6. 2009.02.08 Regular Expression Designer
2009. 4. 30. 19:31

DataTable DataSet DataView Method


DataSet 으로 가져온 데이터를 기반으로 추가로 데이터를 가공할 경우가 필요해서 정리함.

http://www.codeguru.com/forum/showthread.php?t=332574

    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();
    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("ItemPrice = Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();

DataTable.Compute Method
private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable.
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}


Repeater Control and Data Binding - ASP .Net and C#

Introduction:

 Data Binding is the process of creating a link between the data source and the presentation UI to display the data. ASP .Net provides rich and wide variety of controls which can be bound to the data. This model of binding data with the data source reduces a lot of code complexity and increases the ease of maintenance of code. This article looks at how to use this data binding feature for a Repeater control in ASP .Net with C# code.

Repeater Control in ASP .Net:

   A Repeater control is a light weight control which can be used for simple reporting purposes. It supports basic event-handling like Init, Load, Unload etc., This also supports some basic formatting of data and can be presented to the user. A Repeater control offers limited level of data editing or selecting capabilities. For such editing and updates ASP .Net offers DataList and DataGrid controls.

   A Repeater control can be used to build small and Flexible reports with the templates for the items. It supports the following five templates.

  • HeaderTemplate : Can be used to create the Header Rows of the Table data being presented by Repeater control.
  • FooterTemplate : Can be used to create the Footer Rows of the Table data being presented by Repeater control.
  • ItemTemplate : Used for formatting the Items and rows to be displayed.
  • AlternatingItemTemplate : Alternating items formatting.
  • SeparatorTemplate : Styles for separating rows and columns.

   There are many ways in which a control in ASP .Net can be formatted. It is up to the imagination of the programmer to come up with nice formats. For example the Footer rows can be manipulated in such a way that, it can show the summary values or totals etc.,

Repeater Syntax:

<asp:Repeater id="idrepeater" runat="server" Datasource="<%# dataset %>" DataMember="table-inside-dataset">
<HeaderTemplate>..Header Format ..</HeaderTemplate>
<ItemTemplate> .. Item formats .. </ItemTemplate> 
</asp:Repeater>

    As given above, the syntax is simply the Repeater tag with the Template types. These templates can be formatted with ItemStyle tags also.

Using DataBinder.Eval method:

   The System.Web.UI.DataBinder class provides a useful static method DataBinder.Eval, which can be used to evaluate the data at run time using late binding. This function can be used with the Visual Studio IDE or can be manually coded as

 

<%#  DataBinder.Eval(Container.DataItem,"FieldName","Format") %>

   This evaluates and returns the data at run time. This can be used with Repeater, DataList and DataGrid controls though there will be a performance penalty because of the late binding mechanism used.

Creating a Sample Program with Repeater Control:

   Let's create a small sample program with the Repeater control. 

  1. Add a new Webform in an Visual Studio  Asp .net application.
  2. Add a Repeater control to the application. Let us assume that the id of the control is Repeater1.
  3. Insert the following lines of formatting code in between the opening and closing tags of the <asp:Repeater> control.
  4. <HeaderTemplate>
    <table cellpadding="5" cellspacing="2" >
    <tr bgcolor=Gray>
    <td><b>CustomerName</b></td>
    <td><b>Country</b></td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr>
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
    <tr bgcolor="#ccccff">
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
  5. The above code just adds the repeater control with formatting for the header rows, data rows and the footer rows. The HeaderTemplate starts the <table> tag with the table heading and the FooterTemplate closes it.
  6. Now, Add the following code inside the Webform1.aspx.cs, Page_Load event.
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Customer");
    dt.Columns.Add("CustomerName",Type.GetType("System.String"));
    dt.Columns.Add("Country",Type.GetType("System.String"));

    DataRow dr = dt.NewRow();
    dr[0]="Testcustomer1";
    dr[1]="USA";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer2";
    dr[1]="UK";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer3";
    dr[1]="GERMANY";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer4";
    dr[1]="FRANCE";
    dt.Rows.Add(dr);

    //Bind the data to the Repeater
    Repeater1.DataSource = ds;
    Repeater1.DataMember = "Customer";
    Repeater1.DataBind();
  7. The above code creates a dataset to be used with the Repeater control. The repeater's datasource is the Dataset created and the Data member is mentioned as the Table which is created along with the dataset. This enables the Repeater to create the list of items from this customer table.
  8. Now build the application in Visual Studio .Net and load this page. The data will be shown in a tabular format.

   The above sample shows data binding from a statically created data set only. This can be very easily extended to a DataSet generated from database tables, xml files or even DataView s.

   Ultimately, this Repeater control can be used for light weight and simple report generation. This has only a very simple level event handling capabilities. Also there is a performance penalty because of using the DataBinder.Eval methods, this can be considered for data which are not modified frequently. If it is a large amount of data, then caching may be considered to improve the performance, though there are some other factors may have to be considered and not discussed here.

Attachments:

  Project Files : RepeaterSample.zip


Repeater Class


리피터 컨트롤 (Repeater Contorl) 사용시 빈 데이터 핸들링

강력하고 우아한 리피터 컨트롤을 가지고 빈데이터가 왔을경우 어떻게 표시할 수 있는지 그 처리를 위한 기본 메커니즘을 알아봅시다. 예를 들어 다른 컨트롤인 그리드 뷰 같은 경우, 바인드 되는 데이터가 비어있을 경우를 대비해서 그에 관한 속성을 지원합니다. (EmptyDataTemplate)
그렇지만 리피터 컨트롤에는 그와 같은 속성을 지원하지 않습니다. 다만, 리피터 컨트롤의 고유한 유연성으로 이 기능을 추가 시키기 쉽게 되어있습니다. 그럼 데이터가 비었을때 그와 관련된 메시지를 어떻게 나타내주는지 알아보도록 하겠습니다.

아래 예제는 리피터 컨트롤을 사용하여 테이블을 만들어 내는 코드 입니다.

<asp:Repeater runat="server" ID="Repeater1">
    <HeaderTemplate>
        <table width="80%">
    </HeaderTemplate>
    
    <ItemTemplate>
        <tr>
            <td><asp:Label runat="server" Text='<%# Eval("Model") %>' /></td>
        </tr>
    </ItemTemplate>
    
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
 
if (!IsPostBack)
{
    List<Car> cars = new List<Car>();

    Repeater1.DataSource = cars;
    Repeater1.DataBind();
}

만약 위 코드에서 바인딩한 cars 에 빈값이 들어있다면 위 ItemTemplate는 사용되지 않고 리피터 컨트롤은 빈값을 나타내게 됩니다.  아래 코드는 그 결과입니다. Header와 Footer Template만 랜더링 되어있습니다.

<table width="80%">
            
</table>

위에서 보았듣이 Header나 Footer의 경우 데이터의 유/무와 상관없이 랜더링이 됩니다. 이를 이용하여 데이터를 기반으로 하여 빈 데이터시에 그 내용을 나타내 줄 수 있습니다.

아래 코드를 살펴 보겠습니다.

<table width="80%">
    <tr runat="server" 
        visible='<%# ((ICollection)Repeater1.DataSource).Count == 0 ? true : false %>'>
        <td>
            There is no data to display
        </td>
    </tr>

There are a couple of items that should be noted in the above example.

  • The Repeater has been referenced by it's  ID.
  • The DataSource property of the Repeater has been cast to an ICollection object. DataSource is defined as type object, but when data is bound to it, it must be of type ICollection. We are using the Count property from this interface to determine if the "Empty Data" message should display.

When there are several controls where the Visible property needs to be set, the logic can be moved to the code-behind for the page. This is shown in the following IsDataEmpty property.

protected bool IsDataEmpty
{
    get
    {
        ICollection list = Repeater1.DataSource as ICollection;

        return list.Count == 0 ? true : false;
    }
}

The ASPX will change to reference this property as follows:

<table width="80%">
    <tr runat="server" 
        visible='<%# IsDataEmpty %>'>
        <td>
            There is no data to display
        </td>
    </tr>

Regardless of which approach you use, the resulting HTML will now look like:

<table width="80%">
    <tr>
        <td>
            There is no data to display
        </td>
    </tr>   
</table>

As shown in the above examples, it is fairly simple to add HTML that will conditionally render based on the presence (or lack) of data bound to a Repeater.

출처 : http://devcenter.auburnrandall.com/Default.aspx?c=Tech&type=post&id=72


C# DataTable Group by Example

http://programming.top54u.com/post/C-sharp-DataTable-Group-by-Example.aspx

DataTable tbl1 = dset.Tables[0];

DataTable tbl2 = dset.Tables[1];

GridView1.DataSource = tbl2;
GridView1.DataBind();


int counter = 0;

// for each loop to group the records by categoryid
foreach (DataRow dr in tbl2.Rows)
{
    DataView dv = tbl1.DefaultView;
    dv.RowFilter = "categoryid=" + dr["categoryid"];

    GridView grd = (GridView)GridView1.Rows[counter].Cells[0].FindControl("GridView2");

    grd.DataSource = tbl1;
    grd.DataBind();

    counter++;
}




2009. 3. 3. 10:41

정규식을 이용한 숫자입력 체크 함수

내가 만든 숫자입력 체크 정규식
if (!Regex.IsMatch(txtInput.Text, @"^[0-9\.]*$"))
{
    // 숫자 아님
    txtInput.Text = string.Empty;
    txtInput.Select();                                                    
    return;
}
else
{
    // 숫자임
    fnCall();
}


* 단점 : 한글인 경우 체크가 안됩니다....ㅠㅠ

 

// 숫자, 콤마(,), 소숫점(.) 허용한 숫자체크

// 반환값 true / false

function IsNumber(strNumber)
{
    var reg = RegExp(/^(\d|-)?(\d|,)*\.?\d*$/);
    return reg .test(strNumber);
}


// IsNumber함수를 이용한 필드 입력값 체크

// 사용방법 : <input type="text" onkeyup="CheckNumber(this)">

function CheckNumber(field) {
   if( !IsNumber(field.value) )
   {
      alert!("숫자형식만 입력해주십시오.");
      field.value="0";
      field.focus();
      field.select();
   }
}

 

출처 : 몽키님 블로그

 (http://blog.daum.net/monkeychoi/4967162?srchid=BR1http%3A%2F%2Fblog.daum.net%2Fmonkeychoi%F4967162)

2009. 2. 16. 09:59

SQL Server 2005 Database Backup and Restore using C# and .NET 2.0

출처 : http://www.codeproject.com/KB/database/SQL_Server_2005_Database.aspx

Introduction

The following article describes accessing a SQL Server 2005 database backup and restoring it programmatically using C#.NET 2.0 and SMO. This article provides coding samples to perform the task.

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

The following namespaces can be used to access SQL Server 2005 programmatically:

  • Microsoft.SqlServer.management
  • Microsoft.SqlServer.Management.NotificationServices
  • Microsoft.SqlServer.Management.Smo
  • Microsoft.SqlServer.Management.Smo.Agent
  • Microsoft.SqlServer.Management.Smo.Broker
  • Microsoft.SqlServer.Management.Smo.Mail
  • Microsoft.SqlServer.Management.Smo.RegisteredServers
  • Microsoft.SqlServer.Management.Smo.Wmi
  • Microsoft.SqlServer.Management.Trace

Pre-Requisite

You need to reference the following namespaces before using this code:

  • Microsoft.SqlServer.Management.Smo;
  • Microsoft.SqlServer.Management.Common;

I used these two class to perform the backup and restore operations:

  • Microsoft.SqlServer.Management.Smo.Backup
  • Microsoft.SqlServer.Management.Smo.Restore

For more information, regarding these two class, check MSDN:

Backup database

Collapse Copy Code
public void BackupDatabase(String databaseName, String userName, 
            String password, String serverName, String destinationPath)
{
    Backup sqlBackup = new Backup();
    
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "ArchiveDataBase:" + 
                                     DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "Archive";

    sqlBackup.Database = databaseName;

    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);
    
    Database db = sqlServer.Databases[databaseName];
    
    sqlBackup.Initialize = true;
    sqlBackup.Checksum = true;
    sqlBackup.ContinueAfterError = true;
    
    sqlBackup.Devices.Add(deviceItem);
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;

    sqlBackup.SqlBackup(sqlServer);
}

Restore Database

Collapse Copy Code
public void RestoreDatabase(String databaseName, String filePath, 
       String serverName, String userName, String password, 
       String dataFilePath, String logFilePath)
{
    Restore sqlRestore = new Restore();
    
    BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = dataFilePath + databaseName + ".mdf";
    String logFileLocation = logFilePath + databaseName + "_Log.ldf";
    db = sqlServer.Databases[databaseName];
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
    
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += 
       new PercentCompleteEventHandler(sqlRestore_PercentComplete);
            
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();
}

The portion of code uses full backup features. If you want, you can perform incremental and differential backup as well.

Updates: June 8, 2008

In order to use this code, your SQL Server authentication mode needs to be configured as Mixed Mode authentication. If you use Windows Authentication, then you need to modify the ServerConnection:

Collapse Copy Code
SqlConnection sqlCon = new SqlConnection ("Data Source=Bappi; Integrated Security=True;");
ServerConnection connection = new ServerConnection(sqlCon);

Modify the ServerConnection portion of both code samples using this code in order to use Windows Security.

Conclusion

As this code uses the SQL Server 2005 backup/restore facility, the code follows the rules of SQL Server 2005 while backing up or restoring databases.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

2009. 2. 8. 13:00

c# 정규 표현식


출처 : http://cutecars.tistory.com/category

정규 표현식은 책으로도 1권 될 정도로 분량도 많고 복잡하기도 하고 나에겐 매우 어렵다..ㅡ,.ㅡ;

그래서 네이년한테 물어봤더니 쫘~~~~악~~ 그것도 한글로 나오는데 읽어도 읽어도 당췌 뭔소린지

알수가 없다...ㅡ,.ㅡ;;;; 고로 거창하게는 아니고 그냥 프로젝트하다가 적용한 사례 정도만 나중에 혹시

사용할일이 있지 않을까해서 정리해논다(사실 정리 안됨..ㅡ,.ㅡ;;)

본인은 C, C++이 주 언어지만(그렇다고 절대로!! 잘하는건 아님) C#코드로 구현했기 때문에
 
개발자답게(?) 고대로 Copy & Paste와 간단한 설명을 남긴다.

참고로 C#인지 닷넷인지뭔지 몰라도 이놈은 정규식을 완벽히 지원한단다.


using System.Text.RegularExpressions

bool IsVaildStr(string strText)
{
     string Pattern = @"^[a-zA-Z0-9가-힣]*$";
     return Regex.IsMatch(strText, Pattern);
}

간단히 설명하자면 strText의 문자열이 대-소문자 알파벳, 숫자, 한글인지를 체크하는 정규식이다
유저 계정 만들때 사용한 정규식인데 아이디에 특수문자를 사용할수 없게끔하는 식이다
특이하게 한글이 들어간 이유는 모 포탈 사이트에서는(한게임인가로 기억됨...아님 말고...^^)
한글 계정도 지원한다기에 그냥 넣어봤다

자세한 내용은 아래 설명 참조!


※ 정규식 설명 

^
입력의 시작 위치를 의미한다. 여러 줄 모드에서는 줄바꿈 뒤도 의미한다
/^A/
"An A"에서 시작 위치 바로 뒤의 A는 일치하지만 마지막의 A는 일치하지 않는다. 
^[a-z]
 첫 글자는
 반드시 소문자 a-z 사이의 문자를 뜻한다

$
입력의 마지막 위치를 의미한다. 여러 줄 모드에서는 줄바꿈 앞도 의미한다.
/a$/
"Cocoa"에서 마지막에 있는 'a'와 일치한다.
[a-z]$
마지막 글자는 반드시 소문자 a-z사이의 문자를 뜻한다

*
* 앞의 문자가 0번 이상 반복됨을 의미한다.

선택 기호: "|" 기호는 여러 식 중에서 하나를 선택한다.
 "abc|adc"는 abc라는 문자열과 adc라는 문자열을 모두 포함한다.

묶기 기호: (와 )로 여러 식을 하나로 묶을 수 있다.
 "abc|adc"와 "a(b|d)c"는 같은 의미를 가진다. 

[] : [과 ] 사이의 문자 중 하나를 선택한다. "|"를 여러 개 쓴 것과 같은 의미를 가진다. 
[abc]d는 ad, bd, cd를 뜻한다. 또한, "-" 기호와 함께 쓰면 문자의 범위를 지정할 수 있다.
[a-z]는 a부터 z까지 중 하나, [1-9]는 1부터 9까지 중의 하나를 뜻한다.

[^] : [^과 ]  사이의 문자를 제외한 나머지 하나를 선택한다. 
[^abc]d는 ad, bd, cd는 포함하지 않고 ed, fd 등을 포함한다.
[^a-z]는 알파벳 소문자로 시작하지 않는 모든 문자를 나타낸다. 


※ POSIX 문자 그룹(character Classes)

  • [:lower:]   : 소문자 알파벳 문자
  • [:upper:]   : 대문자 알파벳 문자
  • [:digit:]     : 숫자(Numeric digits)
  • [:alnum:]   : 숫자와문자(alphanumeric 문자)
  • [:space:]  : 공백문자(carriage return, newline, vetical tab, form feed)
  • [:punct:]   : 구두점(Punctuation 문자)
  • [:cntl:]     : control 문자
  • [:print:]    : Printable 문자 
  • 2009. 2. 8. 12:57

    C# Regular Expressions

    출처 : http://wpfkorea.egloos.com/654227

    Dos를 사용하던 시절에는 *, !, ?, <>, [] 같은 wildcard 문자를 사용하여 다양한 작업을 했었습니다.
    이 방식은 지금도 unix 계열에서는 사랑받는 방식입니다.
    그리고 현재도 콘솔에서 프로그램 뒤에 파라미터를 넣는 방식은 널리 사용되고 있습니다. 
    정규 표현식은 이런 정의된 문자를 사용해서 패턴을 만들고 그 패턴을 이용해서 원하는 문자를 가져오거나 바꾸는 데 사용되는 방식입니다.

    C#에서도 이런 정규 표현식을 작업하기 쉽도록 지원해 줍니다. 그럼 정규 표현식을 지원하는 클래스 들을 알아보겠습니다.
    일단 정규 표현식 관련 클래스들은 System.Text.RegularExpressions 에 있습니다.
    그리고 System.Text.RegularExpressions 에는 Regex 클래스가 존재합니다.

     Regex 클래스에는 정적 메서드가 여러 개 포합되어 있어서 Regex 개체를 명시적으로 만들지 않고도 정규식을 사용할 수 있습니다.한번 사용한 다음 소멸시킨다는 점에서 정적 메서드를 사용하는 것은 Regex 개체를 만드는 것과 같습니다. Regex 클래스 자체는 스레드로부터 안전하며 읽기 전용으로, 변경할 수 없습니다. , Regex 개체는 모든 스레드에서 만들어질 수 있고 또한 스레드 간에 공유될 수 있으며 관련 메서드는 전역 상태에 전형 영향을 주지 않으면서 모든 스레드에 대해 호출될 수 있습니다. 그러나 Regex 에서 반환하는 Match  MatchCollection 과 같은 결과 개체는 단일 스레드에서만 사용해야 합니다.

     

    Regex 클래스에서 자주 사용되는 메서드들은 다음과 같습니다.

    l  IsMatch(string) - 정규식이 입력 문자열에서 일치하는 항목을 찾을 것인지 여부를 나타냅니다.

    l  Match(string) - 입력 문자열에 정규식이 있는지 검사하고 정확한 결과를 단일 Match 개체로 반환합니다.

    l  Matches(string) - Match를 여러 번 호출한 것처럼 입력 문자열에 있는 정규식을 모두 검색하고 성공적인 일치 항목을 모두 반환합니다.

    l  Replace(pattern, string) - 정규식에 의해 정의된 문자 패턴이 발견되면 지정된 대체 문자열로 모두 바꿉니다.

    l  Split(string, pattern) - 정규식 일치에 의해 정의된 위치에서 부분 문자열로 이루어진 배열로 입력 문자열을 분할합니다.

     

    이제 간단한 예제들을 보여 드리겠습니다.

    언제나 그러하듯 아래 예제들은 제가 msdn 및 기타 사이트 들에서 긁어온 것들을 살짝 변경하였습니다.

     

    IsMatch()  Match() 메서드의 사용법을 알수 있는 예제입니다.
    (http://msdn.microsoft.com/ko-kr/library/system.text.regularexpressions.regex_members(VS.80).aspx)

    using System;

    using System.Text.RegularExpressions;

     

    public class Test

    {

        public static void Main()

        {

            // 정규 표현식을 정의합니다.

            Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");

     

            // 입력될 스트링을 정의합니다.

            string[] tests = { "-42", "19.99", "0.001", "100 USD" };

     

            // 테스트 코드입니다.

            foreach (string test in tests)

            {

                if (rx.IsMatch(test))           

                    Console.WriteLine("{0} is a currency value.", test);           

                else           

                    Console.WriteLine("{0} is not a currency value.", test);           

            }

            Console.ReadLine();

        }

    }












     

     

    이번에도 IsMatch()  Match() 메서드의 사용법을 알수 있는 예제입니다. (http://www.mikesdotnetting.com/Article.aspx?ArticleID=50)

    using System;

    using System.Text.RegularExpressions;

     

    namespace TestCode03

    {

        class Program

        {

            static void Main(string[] args)

            {

                string input = "A12";

     

                //Regex 개체를 생성하는 예제입니다.

                //@"[a-z]\d": 알파벳이 나온  integer 형이 나옵니다.

                //RegexOptions.IgnoreCase: 대소문자를 구문하지 않는 옵션입니다.

                Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

                Match m = re.Match(input);

                if (re.IsMatch(input))

                {

                    Console.Write(m.Value + "\n");

                }

     

                Console.Write(re.IsMatch(input) + "\n");

     

     

                //정정 메소드인 Regex 생성하지 않는 예제입니다.

                Match m2 = Regex.Match(input, @"[a-z]\d");

                if (Regex.IsMatch(input, @"[a-z]\d"))

                {

                    Console.Write(m2.Value + "\n");

                }

     

                Console.Write(Regex.IsMatch(input, @"[a-z]\d") + "\n");

     

                Console.ReadLine();

     

            }

        }

    }


     
     

     









    MatchCollection
     클래스와 Match 클래스의 사용법을 알수 있는 예제입니다.
    (http://msdn.microsoft.com/ko-kr/library/system.text.regularexpressions.regex_members(VS.80).aspx)

    using System;

    using System.Text.RegularExpressions;

     

    public class Test

    {

        public static void Main()

        {

            // 반복을 위한 정규 표현식입니다.

            Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",

              RegexOptions.Compiled | RegexOptions.IgnoreCase);

     

            // 입력되는 문자열입니다.      

            string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

     

            // 일치하는 문자열을 찾습니다.

            MatchCollection matches = rx.Matches(text);

     

            // 표현식과 일치하는 문자열의 갯수를 나타냅니다.

            Console.WriteLine("{0} matches found.", matches.Count);

     

            // 일치한 문자열을 표시합니다.

            foreach (Match match in matches)

            {

                string word = match.Groups["word"].Value;

                int index = match.Index;

                Console.WriteLine("{0} repeated at position {1}", word, index);

            }

            Console.ReadLine();

        }

    }


     








     

    MatchCollection 클래스와 Match 클래스의 사용법을 알수 있는 예제입니다.
    (http://www.mikesdotnetting.com/Article.aspx?ArticleID=50)

    using System;

    using System.Text.RegularExpressions;

     

    namespace TestCode04

    {

        class Program

        {

            static void Main(string[] args)

            {

                string input = "A12 B34 C56 D78";

     

                //Regex 개체를 생성합니다.

                Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

                MatchCollection mc = re.Matches(input);

                foreach (Match mt in mc)

                {

                    Console.Write(mt.ToString() + "\n");

                }

                Console.Write(mc.Count.ToString() + "\n");

     

     

                //Regex 정적클래스 이므로 개체를 생성하지 않아도 됩니다.

                MatchCollection mc2 = Regex.Matches(input, @"[a-z]\d", RegexOptions.IgnoreCase);

                foreach (Match mt in mc)

                {

                    Console.Write(mt.ToString() + "\n");

                }

                Console.Write(mc2.Count.ToString() + "\n");

     

                Console.ReadLine();

            }

        }

    }


     



















    Replace
    메서드의 사용법을 알수 있는 예제입니다. 알파벳을 “XX”로 변환합니다.

    using System;

    using System.Text.RegularExpressions;

     

    namespace TestCode05

    {

        class Program

        {

            static void Main(string[] args)

            {

                string input = @"A12 B34 C56 D78 E12 F34 G56 H78";

     

                //Regex 개체 생성

                Regex re = new Regex(@"[a-z]\d", RegexOptions.IgnoreCase);

                string newString = re.Replace(input, "XX");

                Console.Write(newString);

     

                //Regex 개체를생성하지 않아도 됩니다.

                string newString2 = Regex.Replace(input, @"[A-Z]\d", "XX");

                Console.Write(newString2);

     

                Console.ReadLine();

            }

        }

    } 


     

     









    Split
    메서드의 사용법을 알수 있는 예제입니다. 알파벳을 “XX”로 변환합니다.

    using System;

    using System.Text.RegularExpressions;

     

    namespace TestCode06

    {

        class Program

        {

            static void Main(string[] args)

            {

                string input = "AB1 DE2 FG3 HI4 JK5 LM6 NO7 PQ8 RS9";

     

                //Regex 개체 생성

                Regex re = new Regex(@"\s");

                string[] parts = re.Split(input);

                foreach (string part in parts)

                {

                    Console.Write(part + "\n");

                }

     

                //Regex 개체를생성하지 않아도 됩니다. 스페이스를 기준으로 문자열을 분할합니다.

                string[] parts2 = Regex.Split(input, @"\s");

                foreach (string part2 in parts2)

                {

                    Console.Write(part2 + "\n");

                }

     

                Console.ReadLine();

     

            }

        }

    }


     

     

     
























    End.

    2009. 2. 8. 12:36

    Regular Expression Designer

    출처 : http://pumz.textcube.com/84

    Regular Expression Designer Main Window

    radsoftware사에서 제공하는 아주 유용한 무료 정규식(Regular Expression) 설계 프로그램입니다. 실행하려면 .NET Framework이 필요합니다.

    다양한 예제가 있어서 초보자도 쉽게 쓸 수 있겠네요.

    다운로드: http://www.radsoftware.com.au/regexdesigner/
    .NET Framework 3.5 다운로드: http://msdn.microsoft.com/en-au/netframework/aa569263.aspx
    정규식 배우기: http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

     블로그에서 소개하는 이유는 펌즈 룰 파일에서 정규식을 많이 쓰기 때문이죠. 조만간 펌즈에도 정규식을 테스트할 플러그인을 추가할 계획입니다.