Regular Expression to find a string included betwe

2019-08-12 02:45发布

问题:

I have a string

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

I want to get "name" and "{you}" "{I}" and "do"

if there is a word between two brackets "{{}}" get the word include brackets if only one bracket, just get the word exclude bracket

I tried with

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

Only get the value if the word between 1 bracket {}, if two brackets {{}} the regex match with {{}

please advise

回答1:

You might use \{(\{?[^{}]+}?)}

Explanation

\{       # 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



回答2:

You may try using the following pattern:

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

This pattern essentially captures everything between the two outermost brackets. It accomplishes this using lookarounds which assert on the left and right side of what you intend to capture.

I do not know much Scala, but I did test the above pattern on your test string in Java and it appears to be working.

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



回答3:

Here is the regex pattern from Tim Biegeleisen plugged into the Scala code I think you're looking for.

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}


回答4:

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 ");  
}

}

I found this answer at https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

I think you are looking for something like this.



标签: java regex scala