在Java中使用regex格式化字符串 [英] Format a string using regex in Java

查看:207
本文介绍了在Java中使用regex格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法可以使用正则表达式将字符串格式化为特定模式,或者字符串构建器+子字符串是一种更快的方法吗?

Is there any way I can format a string into a specific pattern using regex or is stringbuilder + substring a faster approach?

例如,说一个电话号码 - - > 1234567890作为输入

For example, say a phone number --> 1234567890 as input

输出为 - >(123)456-7890

And get output as --> (123) 456-7890

我看到了本文有可能: http://www.4guysfromrolla.com/webtech/031302- 1.shtml 但是给出的解释是在ASP中。我怎么用Java做这个?

I saw it is possible on this article : http://www.4guysfromrolla.com/webtech/031302-1.shtml but the given explanation is in ASP. How do I do it in Java ???

推荐答案

一个用于 RE 如果使用 substring 无法完成相同的操作,或者更难以完成。

One goes for RE when same can not be done using substring or is more difficult to do so.

在您的情况下更好只使用 StringBuilder insert()

In your case better to just use StringBuilder and insert()

假设电话号码长度验证到位(= 10个字符)

Assuming phone number length validation is in place (=10 chars)

        String phoneNumber = "1234567890";
        StringBuilder sb = new StringBuilder(phoneNumber)
                                .insert(0,"(")
                                .insert(4,")")
                                .insert(8,"-");
        String output = sb.toString();
        System.out.println(output);          

输出

(123)456-7890

这篇关于在Java中使用regex格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆