码迷,mamicode.com
首页 > 编程语言 > 详细

正则表达式(Java,C#,C++)

时间:2017-11-26 17:51:53      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:imp   tps   util   print   ringbuf   end   tac   pen   append   

Java

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String s = "123-4567-89";
        Pattern r = Pattern.compile("\\d{3}-(\\d{4})-\\d{2}");
        Matcher m = r.matcher(s);
        if (m.find())
            for (int i = 0; i <= m.groupCount(); i++)
                System.out.printf("group %d : %s\n", i, m.group(i));

        // https://stackoverflow.com/questions/19737653/what-is-the-equivalent-of-regex-replace-with-function-evaluation-in-java-7
        r = Pattern.compile("\\d+");
        m = r.matcher(s);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, new StringBuffer(m.group(0)).reverse().toString());
        }
        m.appendTail(sb);
        System.out.println(sb.toString());

        r = Pattern.compile("%(begin|next|end)%");
        s = "%begin%hello%next%world%end%";
        System.out.println(Arrays.asList(r.split(s)));
    }
}

/*
group 0 : 123-4567-89
group 1 : 4567
321-7654-98
[, hello, world]
 */

C

using System;
using System.Text.RegularExpressions;

namespace Sample
{
    class Test
    {
        public static void Main(string[] args)
        {
            var r = new Regex(@"\d{3}-(\d{4})-\d{2}");
            var s = "123-4567-89";
            var m = r.Match(s);
            foreach (Group g in m.Groups)
                Console.WriteLine($"group {g.Index} : {g.Value}");
            
            r = new Regex(@"\d+");
            s = r.Replace(s, m2 => {
                var arr = m2.Groups[0].Value.ToCharArray();
                Array.Reverse(arr);
                return new string(arr);
            });
            Console.WriteLine(s);

            r = new Regex("%(?:begin|next|end)%");
            s = "%begin%hello%next%world%end%";
            foreach (var s2 in r.Split(s))
                Console.WriteLine(s2);
        }
    }
}

/*
group 0 : 123-4567-89
group 4 : 4567
321-7654-98

hello
world


*/

正则表达式(Java,C#,C++)

标签:imp   tps   util   print   ringbuf   end   tac   pen   append   

原文地址:http://www.cnblogs.com/zwvista/p/7899250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!