简体   繁体   中英

Need help in figuring out the right regex pattern

I need to extract substrings from a string:

Given string: "< If( ( h == v ) ): { [ < j = (i - f) ;>, < k = (g + t) ;> ] }>" I need two substrings: "j = (i - f)" and "k = (g + t)" .

For this I tried user pattern regex. Here's my code:

Pattern pattern = Pattern.compile("[<*;>]");
Matcher matcher = pattern.matcher(out.get(i).toString());
while (matcher.find())
     {
        B2.add(matcher.group());
      }

out.get(i).toString() is my input string. B2 is an ArrayList which will contain the two extracted substrings.

But, after running the above code, the output I am getting is : [<, <, ;, >, <, ;, >, >] .

My pattern is not working! Your help is very much appreciated. Thanks in advance!

You can use the expression <([^<]+);> .

This will match things between < and ;>

Pattern pattern = Pattern.compile("<([^<]+);>");
Matcher matcher = pattern.matcher(out.get(i).toString());
while (matcher.find())
     {
        B2.add(matcher.group(1));
      }

You can see the results on regexplanet: http://fiddle.re/5rty6

your [ and ] are causing you problems. those symbols mean: "match one among the symbols inside of these" If you remove those, you'll get better results. You'll also have to escape your pointy brackets when you do that.

The next step will be to capture the groups. you normally use ( and ) for that.

You'll also have to worry about nasty artifacts such as that < at the beginning of the string which will mess with your regex. in order to deal with that, you'll need to exclude those from your regex.

You might end up with

"\<([^<>]*?)\>"

as your regex. Be sure to check the specific java documentation and to escape your \\ for a final result of

"\\<([^<>]*?)\\>"

If you're wanting to next other < and > inside your pointy brackets, regex has a lot of trouble with that kind of thing, and maybe you should try a different method

Here's a sample regex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM