Show toolbar
顯示具有 RegEx 標籤的文章。 顯示所有文章
顯示具有 RegEx 標籤的文章。 顯示所有文章

2019年11月12日 星期二

Mask String

標題:Mask String
JavaScript (maskString.js):
const maskString = (str, style) => {
  switch (style) {
    case "email":
      // abcde@gmail.com => a***e@g*******m
      return str.replace(/([^@]+)/g, s => maskString(s));
    default:
      // abcde => a***e
      return str.replace(/(?<=.).(?=.*?.)/g, "*");
  }
};

const str = maskString("abcd1234@gmail.com", "email");
console.log(str);

範例:

a******4@g*******m

說明:
遮罩第1個字與最後1個字以外的字元。

2014年7月14日 星期一

Regular Expression Iterator

標題:使用迭代器匹配字串
VC++ (regex.cpp):
#include <iostream>
#include <regex> //string lib here
using namespace std;

int main(int argc, char* argv[])
{
    string str = "facet normal -8.944272e-001 4.472136e-001 0.000000e+000";
    regex pattern("[+-]?[0-9]\\.[0-9]+[eE][+-]?[0-9]+");

    auto words_begin = sregex_iterator(str.begin(), str.end(), pattern);
    auto words_end = sregex_iterator();

    cout << "Found " << std::distance(words_begin, words_end) << " numbers:\n";

    for (sregex_iterator i = words_begin; i != words_end; ++i) {
        cout << atof( ((smatch) *i).str().c_str() ) << '\n';
    }

    system("pause");
    return 0;
}


說明:
使用迭代器匹配字串。

Regular Expression to match IP Address

標題:使用正規表示法驗證IP
VC++ (regex.cpp):
#include <iostream>
#include <regex> //string lib here
using namespace std;

int main(void) {
    string ip = "192.168.1.100";
    smatch results;
    regex pattern("([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)");
    if(regex_match(ip, results, pattern)) {
        cout << atof( results[1].str().c_str() ) << endl;
        cout << atof( results[2].str().c_str() ) << endl;
        cout << atof( results[3].str().c_str() ) << endl;
        cout << atof( results[4].str().c_str() ) << endl;
    } else {
        cout << "Not Match." << endl;
    }
    system("pause");
    return 0;
}

說明:
簡單使用正規表示法驗證IP,並印出每個區段數值。

2014年7月2日 星期三

Simple Regular expression

標題:基本正規表示法
VC++ (regex.cpp):
#include <iostream>
//#include <string>
#include <regex> //string lib here
using namespace std;

int main(void)
{
    int r = 0;
    string number = "";

    //匹配模型
    regex number_format("[0-9]{1,5}");

    //隨機數
    srand(time(NULL));
    r = rand()%10;

    cout << "Input number:" << endl;
    cin >> number;

    //資料比對
    if(regex_match(number, number_format)) {
        cout << number << " * " << r << " = " << stoi(number) * r << endl;
    } else {
        cout << "Not match." << endl;
    }

    system("pause");
    return 0;
}

說明:
基本的正規表示法進行數字的匹配,並乘上一隨機數。

2013年8月16日 星期五

Encryption in Node.JS using crypto

標題:在Node.JS中使用加密
Node.JS (encryption.js):

範例輸出:

說明:
crypto模組在Node.JS為原生Module可直接使用,切勿再使用npm安裝或使用相對路徑require,最後為使用Regular expression比對base64格式。

2013年7月18日 星期四

Read STL Model file and export graphics using GD Library

標題:讀取STL模型檔案並使用GD Library匯出圖形
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <regex>
#include <fstream>
#include "gd/gd.h"
#include "gd/gdfontg.h"
#include "gd/gdfontt.h"
#include "gd/gdfonts.h"
#include "gd/gdfontmb.h"
#include "gd/gdfontl.h"
#pragma comment(lib, "lib/bgd.lib")
using namespace std;

class pos
{
public:
    float x;
    float y;
    float z;
};

class ERR
{
private:
    int kind;
public:
    ERR(int k) : kind(k){}; //建構函式
    char* message()
    {
        switch(kind)
        {
        case 0:
            return "Parameter Error!";
        case 1:
            return "Path Error!";
        case 2:
            return "File Error!";
        case 3:
            return "Array Size is too small.";
        case 4:
            return "STL Format Error!";
        }
    }
};

void draw(gdImagePtr im, pos vArr[], int v, int color)
{
    int i = 0;
    for(i=0;i<v;i+=3)
    {
        gdImageLine(im, (int)vArr[i].x, (int)vArr[i].y, (int)vArr[i+1].x, (int)vArr[i+1].y, color);
        gdImageLine(im, (int)vArr[i+1].x, (int)vArr[i+1].y, (int)vArr[i+2].x, (int)vArr[i+2].y, color);
        gdImageLine(im, (int)vArr[i].x, (int)vArr[i].y, (int)vArr[i+2].x, (int)vArr[i+2].y, color);
    }
}

int main(int argc, char* argv[])
{
    const float zoom = 5;
    const int arrSize = 3000;
    const int width = 500;
    const int height = 500;
    int i = 0, normals = 0, vertexs = 0;
    char pathChar[1024];
    char stlName[1024];
    string lines = "";

    pos *normalArr;
    pos *vertexArr;

    regex pathRegex("([a-zA-Z]\:\\\\(?:[^\\\\]+\\\\)*)(.*)"); //"C:\\temp\\hello.txt"
    regex solid(" *solid.*");
    regex facetNormal(" *facet normal ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
    regex outerLoop(" *outer loop");
    regex vertex(" *vertex ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) ([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
    regex endLoop(" *endloop");
    regex endfacet(" *endfacet");
    regex endsolid(" *endsolid");
    
    cmatch pathMatch;
    smatch normalMatch;
    smatch vertexMatch;

    try
    {
        if(argc<2) throw ERR(1); //Check Parameter

        strcpy(pathChar, argv[1]); //Get STL Path
        if(!regex_match(pathChar, pathMatch, pathRegex)) throw ERR(1); //Check STL Path

        strcpy(stlName, pathMatch[2].str().c_str()); //Get STL Name

        ifstream File(pathChar);
        if (!File.is_open()) throw ERR(2); //Check File

        normalArr = new pos[arrSize]; //宣告Facet normal動態陣列大小
        vertexArr = new pos[arrSize*3]; //宣告Vertex動態陣列大小

        cout << "Reading Now..." << endl;

        //solid
        if(!File.good())  throw ERR(4);
        getline(File, lines);
        if(!regex_match(lines, solid)) throw ERR(4);

        while(File.good())
        {
            if(normals >= arrSize) throw ERR(3); //Check Array Size

            //facet normal
            getline(File, lines);
            if(regex_match(lines, normalMatch, facetNormal))
            {
                normalArr[normals].x = atof(normalMatch[1].str().c_str()) + width/2;
                normalArr[normals].y = atof(normalMatch[2].str().c_str()) + height/2;
                normalArr[normals].z = atof(normalMatch[3].str().c_str());
                normals++;
            }
            else if(regex_match(lines, endsolid)) //end solid
            {
                break;
            }
            else
            {
                throw ERR(4);
            }
 
            //outer loop
            getline(File, lines);
            if(!regex_match(lines, outerLoop)) throw ERR(4);
 
            //vertex
            for(i=0;i<3;i++)
            {
                getline(File, lines);
                if(regex_match(lines, vertexMatch, vertex))
                {
                    vertexArr[vertexs].x = atof(vertexMatch[1].str().c_str())*zoom + width/2;
                    vertexArr[vertexs].y = atof(vertexMatch[2].str().c_str())*zoom + height/2;
                    vertexArr[vertexs].z = atof(vertexMatch[3].str().c_str())*zoom;
                    vertexs++;
                }
                else
                {
                    throw ERR(4);
                }
            }
 
            //end loop
            getline(File, lines);
            if(!regex_match(lines, endLoop)) throw ERR(4);
 
            //end facet
            getline(File, lines);
            if(!regex_match(lines, endfacet)) throw ERR(4);
        }
        File.close();

        cout << "Facet Normal: " << normals << endl;
        cout << "Vertex: " << vertexs << endl;
        cout << "Done." << endl;

        // --- draw ---
        cout << "Drawing Now..." << endl;

        FILE *out;
        int size;
        char *data;
 
        gdImagePtr im = gdImageCreate(width, height);
     
        int white =  gdImageColorAllocate(im, 255, 255, 255), //Background
            black =  gdImageColorAllocate(im, 0, 0, 0),
            blue =   gdImageColorAllocate(im, 0, 0, 255),
            cyan =   gdImageColorAllocate(im, 0, 255, 255),
            green =  gdImageColorAllocate(im, 128, 255, 0),
            red =    gdImageColorAllocate(im, 255, 0, 0),
            purple = gdImageColorAllocate(im, 255, 0, 255),
            orange = gdImageColorAllocate(im, 255, 128, 0),
            yellow = gdImageColorAllocate(im, 255, 255, 0);
 
        strcpy(pathChar, argv[0]); //Get Execution Path
        if(!regex_match(pathChar, pathMatch, pathRegex)) throw ERR(1); //Check Execution Path
        strcpy(pathChar, pathMatch[1].str().c_str()); //Get Folder Path
        strcat(pathChar, stlName); //Connections Folder Path and STL Name
        strcat(pathChar, ".png"); //Connections Path and Extension

        out = fopen(pathChar, "wb");
        if (!out) throw ERR(1);

        draw(im, vertexArr, vertexs, black);

        data = (char *) gdImagePngPtr(im, &size);
        if (!data) throw ERR(2);

        if (fwrite(data, 1, size, out) != size) throw ERR(3);

        if (fclose(out) != 0) throw ERR(4);
        gdFree(data);
        cout << "Done." << endl;
    }
    catch(ERR e)
    {
        cout << e.message() << endl;
    }
    system("pause");

    return 0;
}

說明:
首先拖曳一個STL模型檔案至執行檔以進行讀取,一邊進行檔案比對一邊將點資料存入類別陣列內,再使用GD Library匯出png圖片檔。

Solving Matrix Inverse using Pointer

標題:使用指標求解n維矩陣
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <iomanip>
using namespace std;

void print(double *Arr, int m)
{
    int i = 0, j = 0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<m;j++)
        {
            cout << *(Arr+i*m+j) << setprecision(2) << "\t";
        }
        cout << endl;
    }
}
void printInverse(double *Matrix, double *Inverse, int m)
{
    int i = 0, j = 0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<m;j++)
        {
            cout << *(Matrix+i*m+j) << setprecision(2) << "\t";
        }
        cout << "|\t";
        for(j=0;j<m;j++)
        {
            cout << *(Inverse+i*m+j) << setprecision(2) << "\t";
        }
        cout << endl;
    }
}

void readfile(string filePath, double *Matrix)
{
    int m = 0, n = 0, i = 0;
    string lines = "";
    string::const_iterator start;
    match_results<string::const_iterator> matchMatrix; //迭代器
    regex regMatrix("([0-9]+)+");
    ifstream outputFile(filePath);
    if (outputFile.is_open()) //Check File
    {
        while(outputFile.good())
        {
            getline(outputFile, lines);
            start = lines.begin();
            while (regex_search(start, lines.cend(), matchMatrix, regMatrix))
            {
                *(Matrix+i) = atof(matchMatrix[1].str().c_str());
                i++;
                start = matchMatrix[0].second;
            }
            m++;
        }
        outputFile.close();
    }
}
double plusnum(double num)
{
    if(num < 0) return -1 * num;
    return num;
}

void rowSwap(double *Matrix, int ma, int mb, int m)
{
    int i = 0;
    double *Temp = new double[m];
    for(i=0;i<m;i++)
    {
        *(Temp+i) = *(Matrix+ma*m+i);
        *(Matrix+ma*m+i) = *(Matrix+mb*m+i);
        *(Matrix+mb*m+i) = *(Temp+i);
    }
}

void inverse(double *Matrix, double *Inverse, int m)
{
    int i = 0, j = 0, k = 0;
    double temp = 0;
    //*(Matrix + rows * m + columns) 看成 Matrix[rows][columns]
    for(int i=0; i<m; i++)
    {
        for(int j=i+1; j<m; j++)
        {
            if(plusnum(*(Matrix + j * m + i)) > plusnum(*(Matrix + i * m + i)))
            {
                rowSwap(Matrix, i, j, m); // 互換Matrix矩陣兩行
                rowSwap(Inverse, i, j, m); // 互換Inverse矩陣兩行
                //cout << "[" << i << "][" << j << "]Swap:" << endl;
                //printInverse(Matrix, Inverse, m);
            }
        }
        // 消去
        for(int j=0; j<m; j++) //第 i 次消去運算,以第 i 行作為主要行,將其上下各行的第 i 列元素化為零
        {
            if(j != i)
            {
                // 進行消去運算,將第 i 列上下方的元素化為零
                double temp = *(Matrix + j * m + i) / *(Matrix + i * m + i);
                
                // 注意此處 k 可從 i+1 開始
                //for(int k=i+1; k<m; k++)
                for(int k=0; k<m; k++)
                {
                    *(Matrix + j * m + k) -= (*(Matrix + i * m + k) * temp);
                }
                // 注意此處 k 要從 0 開始
                for(int k=0; k<m; k++)
                {
                    *(Inverse + j * m + k) -= (*(Inverse + i * m + k) * temp);
                }
                //cout << "[" << i << "][" << j << "]Matrix:" << endl;
                //printInverse(Matrix, Inverse, m);
            }
        }
    }

    // Matrix 已經是對角矩陣,只要在將其對角線元素化為 1 即可
    // 此時僅需對 Inverse 矩陣作運算
    //cout << "[" << i << "][" << j << "]Inverse:" << endl;
    //printInverse(Matrix, Inverse, m);
    for(int i=0; i<m; i++)
    {
        for(int j=0; j<m; j++)
        {
            *(Inverse + i * m + j) /= *(Matrix + i * m + i);
        }
        //cout << "[" << i << "][" << j << "]Inverse:" << endl;
        //printInverse(Matrix, Inverse, m);
    }
}
 
int main(int argc, char *argv[])
{
    const int m = 4;
    int i = 0, j = 0;
    double Matrix[m][m] = {};
    double Inverse[m][m] = {};

    for(i=0;i<m;i++)
    {
        for(j=0;j<m;j++)
        {
            if(i == j)
                Inverse[i][j] = 1;
            else
                Inverse[i][j] = 0;
        }
    }
    
    readfile("matrix.txt", &Matrix[0][0]);

    cout << "Matrix:" << endl;
    print(&Matrix[0][0], m);

    inverse(&Matrix[0][0], &Inverse[0][0], m);
    cout << endl;
 
    cout << "Inverse:" << endl;
    print(&Inverse[0][0], m);

    system("pause");
    return 0;
}
TEXT (matrix.txt):

說明:
先讀取矩陣數據再利用指標的方式求得n維度反矩陣的解。

2013年7月16日 星期二

Check the ASCII format of STL file

標題:檢查ASCII STL格式範例
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <regex> //string lib here

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0, num = 1;
    const char *filePath = "TriangleASCII.STL";
    string lines = "";

    regex solid(" *solid.*");
    regex facetNormal(" *facet normal .+ .+ .+");
    regex outerLoop(" *outer loop");
    regex vertex(" *vertex .+ .+ .+");
    regex endLoop(" *endloop");
    regex endfacet(" *endfacet");
    regex endsolid(" *endsolid");
    //regex number("[+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?");

    ifstream outputFile(filePath);
    if (outputFile.is_open()) //Check File
    {
        num++;
        //solid
        if(outputFile.good())
        {
            getline(outputFile, lines);
            if(regex_match(lines, solid))
            {
                cout << lines << endl;

                while(outputFile.good())
                {
                    //facet normal
                    getline(outputFile, lines);
                    if(regex_match(lines, facetNormal))
                    {
                        cout << lines << endl;
                        num++;
                    } else if(regex_match(lines, endsolid)) { //end solid
                        cout << lines << endl;
                        cout << "Done." << endl;
                        break;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }

                    //outer loop
                    getline(outputFile, lines);
                    if(regex_match(lines, outerLoop))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }

                    //vertex
                    getline(outputFile, lines);
                    if(regex_match(lines, vertex))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }
                
                    getline(outputFile, lines);
                    if(regex_match(lines, vertex))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }
                
                    getline(outputFile, lines);
                    if(regex_match(lines, vertex))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }

                    //end loop
                    getline(outputFile, lines);
                    if(regex_match(lines, endLoop))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }

                    //end facet
                    getline(outputFile, lines);
                    if(regex_match(lines, endfacet))
                    {
                        cout << lines << endl;
                        num++;
                    } else {
                        cout << "[line " << num << " format error] " << lines << endl;
                        break;
                    }
                }
            } else {
                cout << "[line " << num << " format error] " << lines << endl;
            }
        }
        outputFile.close();
    }

    return 0;
}
說明:
使用Regular Expression檢查ASCII STL檔案格式。

2013年7月15日 星期一

Exception Handling

標題:例外處理的方法
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <regex>
#include <fstream>
using namespace std;

class pos
{
public:
    float x;
    float y;
    float z;
};

class ERR
{
private:
    int kind;
public:
    ERR(int k) : kind(k){}; //建構函式
    char* message()
    {
        switch(kind)
        {
        case 0:
            return "Error A";
        case 1:
            return "Error B";
        case 2:
            return "Error C";
        }
    }
};

void readfile(string path)
{
    string lines = "";
    ifstream File(path);
    if (File.is_open()) //Check File
    {
        while(File.good())
        {
            getline(File, lines);
            cout << lines << endl;
        }
        File.close();
    }
}

int main(int argc, char *argv[])
{
    switch(0) //Select Example
    {
    case 0:
        {
            //Example 1
            int n = 0;
            string str = "Hello";
            try
            {
                cin >> n;
                cout << str.at(n) << endl; //取得字串的第n個字元
            }
            catch (...)
            {
                cout << "Error!" << endl;
            }
            break;
        }
    case 1:
        {
            //Example 2
            float num = 1;
            try
            {
                cout << "num=";
                cin >> num;
                if(num == 0)
                {
                    throw "Infinity!";
                }
                cout << "100/num=" << 100/num << endl;
            }
            catch (const char* message)
            {
                cout << message << endl;
            }
            break;
        }
    case 2:
        {
            //Example 3
            try {
                if(argc<2)
                {
                    throw "Parameter error.";
                }
                char pathChar[1024];
                regex pathRegex("([a-zA-Z]\:\\\\(?:[^\\\\]+\\\\)*.*)"); //"C:\\temp\\hello.txt"
                cmatch pathMatch; //cmatch: Char Match
                strcpy(pathChar, argv[1]); //Pointer to Char
                if(regex_match(pathChar, pathMatch, pathRegex)) //char, cmatch, regexp
                {
                    readfile(pathMatch[1].str());
                }
                else
                {
                    throw "Path Error.";
                }
            }
            catch(const char* message)
            {
                cout << message << endl;
            }
            break;
        }
    case 3:
        {
            //Example 4
            pos p;
            p.x = 1.1f;
            p.y = 2.2f;
            p.z = 3.3f;
            cout << "(" << p.x << ", " << p.y << ", " << p.z << ")" << endl;
            break;
        }
    case 4:
        {
            //Example 5
            try
            {
                throw ERR(0);
            }
            catch(ERR e)
            {
                cout << e.message() << endl;
            }
            break;
        }
    }

    system("pause");
    return 0;
}

說明:
一般及搭配argc、argv、Regular Expression、Class例外處理的方法

2013年7月10日 星期三

Get value using Regular Expression

標題:C/C++使用正規表示法取值
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <regex> //string lib here

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "--- Example 1 ---" << endl;
    //String Match
    string strA = "13393774";
    smatch matchA;
    regex regA("[0-9]+");
    if(regex_match(strA, matchA, regA))
    {
        cout << atof(matchA[0].str().c_str()) << " is number." << endl;
    } else {
        cout << "Not a number." << endl;
    }

    cout << "--- Example 2 ---" << endl;
    //String Match
    string strB = "-4.472136e-001";
    smatch matchB;
    regex regB("[+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?");
    if(regex_match(strB, matchB, regB))
    {
        cout << atof(matchB[0].str().c_str()) << " is number." << endl;
    } else {
        cout << "Not a number." << endl;
    }
    
    cout << "\n--- Example 3 ---" << endl;
    //String Search
    string strC = "   facet normal 0.000000e+000 -4.472136e-001 8.944272e-001";
    smatch matchC;
    regex regC(" *facet normal \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?) \
([+-]?(?=\.[0-9]|[0-9])(?:[0-9]+)?(?:\.?[0-9]*)(?:[eE][+-]?[0-9]+)?)");
    if(regex_match(strC, matchC, regC))
    {
        cout << "Facet normal: (";
        cout << atof(matchC[1].str().c_str()) << ", ";
        cout << atof(matchC[2].str().c_str()) << ", ";
        cout << atof(matchC[3].str().c_str()) << ")" << endl;
    } else {
        cout << "Not Match." << endl;
    }

    return 0;
}

說明:
在C/C++中使用正規表示式取得數值。

2013年7月8日 星期一

Using Regular expression in C/C++

標題:C/C++使用正規表示法
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <regex> //string lib here

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //String Match
    string strA = "1337";
    regex regA("[0-9]+");
    if(regex_match(strA, regA))
    {
        cout << "A Match." << endl;
    } else {
        cout << "A Not Match." << endl;
    }

    //String Search
    string strB = "cad23342";
    regex regB("[0-9]");
    if(regex_search(strB, regB))
    {
        cout << "B Match." << endl;
    } else {
        cout << "B Not Match." << endl;
    }

    //String Replace
    string strC = "Hello I'm QQBoxy!!";
    regex regC(" ");
    string wordC = "\n";
    cout << regex_replace(strC, regC, wordC) << endl;

    //String Replace
    string strD = "Hello I'm QQBoxy!!";
    regex regD("a|e|i|o|u");
    string wordD = "[$&]";
    cout << regex_replace(strD, regD, wordD) << endl;

    return 0;
}
說明:
在C/C++中正規表示式常用的三種語法。

2013年1月25日 星期五

C# Regex Double Backslash

標題:C#使用雙反斜線表示特殊字元
C# (Main.cs):
Regex solidVcg = new Regex("^\\s*solid\\svcg$");

說明:
在C#撰寫特殊字元如\s時,
若只有一個反斜線Visual Studio C#會報錯,
如下圖:

這時候必須使用雙反斜線來表示就能正常執行。

2012年12月3日 星期一

C# WPF RegEx Check Number

標題:使用RegEx進行數字比對
C# (MainWindow.xaml.cs):
using System;
using System.Windows;
using System.Text.RegularExpressions; //RegEx

namespace WPFRegEx {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }
        public void CheckRegEx(string text) {
            Regex regex = new Regex("^[0-9]+$"); //建立RegEx規則
            Match result = regex.Match(text); //字串比對
            if (result.Success) {
                System.Windows.MessageBox.Show("True");
            } else {
                System.Windows.MessageBox.Show("False");
            }
        }
        private void btn_Click(object sender, RoutedEventArgs e) {
            CheckRegEx(tbx.Text);
        }
    }
}
WPF (MainWindow.xaml.cs):
<Window x:Class="WPFRegEx.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="30" Margin="20,20,20,0" Name="tbx" VerticalAlignment="Top" />
        <Button Content="Button" Height="30" Margin="20,70,20,0" Name="btn" VerticalAlignment="Top" Click="btn_Click" />
    </Grid>
</Window>

範例結果:


說明:
在C# WPF使用RegEx判斷字串是否為數字之基礎範例。