正则表达式查找两个括号之间的字符串

时间:2018-02-14 04:06:03

标签: java regex scala

我有一个字符串

String a = "Hello my {name} , how are {{you}}, what should {{I}} {do}"

我想得到"姓名"和" {you}" " {I}"和"做"

如果两个括号之间有单词" {{}}"得到包含括号的单词 如果只有一个括号,只需获得单词exclude bracket

我试过

    val pattern = "\\{(.*?)\\}".r
    pattern.replaceAllIn(valName, m => { // my condition } )

只有当1个方括号{}之间的单词时,如果正则表达式{{}}与 {{}

匹配,则只获取值

请告知

4 个答案:

答案 0 :(得分:2)

您可以尝试使用以下模式:

(?<=(?:[^{]|^)\{).*?(?=\}(?:[^}]|$))

这种模式基本上捕获了两个最外面的括号之间的所有内容。它使用在您想要捕获的内容的左侧和右侧断言的外观来实现此目的。

我不太了解Scala,但我确实用Java测试了你的测试字符串上面的模式,它似乎正在工作。

Demo

String input = "{{Hello}} my {name} , how are {{you}}, what should {{I}} {do}";
Pattern p = Pattern.compile("(?<=(?:[^{]|^)\{).*?(?=\}(?:[^}]|$))");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    String rp = "";
    switch (m.group(0)) {
        case "name":
            rp = "Tim";
            break;

        case "{you}":
            rp = "Aditya";
            break;
    }
    m.appendReplacement(sb, rp);
}
m.appendTail(sb);
System.out.println(sb.toString());

Demo

答案 1 :(得分:1)

以下是来自Tim Biegeleisen的正则表达式模式,插入到我认为您正在寻找的Scala代码中。

val str = "Hello my {name} , how are {{you}}, what should {{I}} {do}"

val pttrn = "(?<=(?:[^{]|^)\\{).*?(?=\\}(?:[^}]|$))"

pttrn.r.replaceAllIn(str, x => if (x.matched == "name") "A" else "B")
//res0: String = Hello my {A} , how are {B}, what should {B} {B}

答案 2 :(得分:1)

您可以使用\{(\{?[^{}]+}?)}

<强>解释

\{       # match {
(        # Capture in a group
  \{?    # Optional {
  [^{}]+ # Match not {} one or more times
  }?     # Match optional }
)        # Close capturing group
}        # match }

val a = "Hello my {name} , how are {{you}}, what should {{I}} {do}"
val pattern = """\{(\{?[^{}]+}?)}""".r
val result = pattern.replaceAllIn(a, m =>
  m.group(1) match {
    case "name" => "nameHere"
    case _ => m.group(1)
  }
)

Scala demo output

答案 3 :(得分:0)

public class Test {
static class stack 
{
    int top=-1;
    char items[] = new char[100];

    void push(char x) 
    {
        if (top == 99) 
        {
            System.out.println("Stack full");
        } 
        else
        {
            items[++top] = x;
        }
    }

    char pop() 
    {
        if (top == -1) 
        {
            System.out.println("Underflow error");
            return '\0';
        } 
        else
        {
            char element = items[top];
            top--;
            return element;
        }
    }

    boolean isEmpty() 
    {
        return (top == -1) ? true : false;
    }
}

/* Returns true if character1 and character2
   are matching left and right Parenthesis */
static boolean isMatchingPair(char character1, char character2)
{
   if (character1 == '(' && character2 == ')')
     return true;
   else if (character1 == '{' && character2 == '}')
     return true;
   else if (character1 == '[' && character2 == ']')
     return true;
   else
     return false;
}

/* Return true if expression has balanced 
   Parenthesis */
static boolean areParenthesisBalanced(char exp[])
{
   /* Declare an empty character stack */
   stack st=new stack();

   /* Traverse the given expression to 
      check matching parenthesis */
   for(int i=0;i<exp.length;i++)
   {

      /*If the exp[i] is a starting 
        parenthesis then push it*/
      if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
        st.push(exp[i]);

      /* If exp[i] is an ending parenthesis 
         then pop from stack and check if the 
         popped parenthesis is a matching pair*/
      if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
      {

          /* If we see an ending parenthesis without 
             a pair then return false*/
         if (st.isEmpty())
           {
               return false;
           } 

         /* Pop the top element from stack, if 
            it is not a pair parenthesis of character 
            then there is a mismatch. This happens for 
            expressions like {(}) */
         else if ( !isMatchingPair(st.pop(), exp[i]) )
           {
               return false;
           }
      }

   }

   /* If there is something left in expression 
      then there is a starting parenthesis without 
      a closing parenthesis */

   if (st.isEmpty())
     return true; /*balanced*/
   else
     {   /*not balanced*/
         return false;
     } 
} 

/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
public static void main(String[] args) 
{
    char exp[] = {'{','(',')','}','[',']'};
      if (areParenthesisBalanced(exp))
        System.out.println("Balanced ");
      else
        System.out.println("Not Balanced ");  
}

}

我在https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

找到了这个答案

我认为你正在寻找类似的东西。