【问题标题】:How to negate inverse a regex expression如何否定逆正则表达式
【发布时间】:2011-10-11 03:21:12
【问题描述】:

我正在使用 Java 正则表达式。 我有一个字符串如下

String s = "the location is at {emp.address.street} with the name {emp.name},{emp.surname}";

对于上述字符串,s.replaceAll( "\\{(.*?)\\}", "" ) 返回以下字符串:

the location is at with the name ,

现在我想反演得到以下结果:

{emp.address.street}{emp.name}{emp.surname}

【问题讨论】:

    标签: java regex replace inverse


    【解决方案1】:

    这个经过测试的脚本对我有用:

    public class TEST
    {
        public static void main( String[] args )
        {
            String s = "the location is at {emp.address.street} with the name {emp.name},{emp.surname}";
            String result = s.replaceAll( "[^{}]+|(\\{(.*?)\\})", "$1" );
            System.out.println(result);
        }
    }
    

    【讨论】:

    • 太好了...您能解释一下它是如何工作的吗? $1 的作用是什么?
    【解决方案2】:

    您可以创建一个Pattern 并使用Matcher.find()Matcher.group() 来获取该模式的一部分。 以下是这些类的 Javadocs:Matcher javadocPattern javadoc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      相关资源
      最近更新 更多