简体   繁体   中英

Regular expression help in java

I am lost when it comes to building regex strings. I need a regular expression that does the following.

I have the following strings:

[~class:obj]
[~class|class2|more classes:obj]
[!class:obj]
[!class|class2|more classes:obj]
[?method:class]
[text]

A string can have multiple of whats above. Example string would be "[if] [!class:obj]"

I want to know what is in between the [] and broken into match groups. For example, the first match group would be the symbol if present (~|!|?) next what is before the : so that could be class or class|class2|etc... then what is on the right of the : and stop before the ]. There may be no : and what goes before it, but just something between the [].

So, how would I go about writing this regex? And is it possible to give the match group names so I know what it matched?

This is for a java project.

Thanks in advanced.

If you're sure enough of your inputs, you can probably use something like /\\[(\\~|\\!|\\?)?(?:((?:[^:\\]]*?)+):)?([^\\]]+?)\\]/ . (to translate that into Java, you'll want to escape the backslashes and use quotation marks instead of forward slashes)

I believe that this should work:

/[(.*?)(?:\|(.*?))*]/

Also:

[a-z]*

Try this code

final Pattern
  outerP = Pattern.compile("\\[.*?\\]"),
  innerP = Pattern.compile("\\[([~!?]?)([^:]*):?(.*)\\]");
for (String s : asList(
    "[~class:obj]",
    "[if][~class:obj]",
     "[~class|class2|more classes:obj]",
     "[!class:obj]",
     "[!class|class2|more classes:obj]",
     "[?method:class]",
     "[text]"))
{
  final Matcher outerM = outerP.matcher(s);
  System.out.println("Input: " + s);
  while (outerM.find()) {
    final Matcher m = innerP.matcher(outerM.group());
    if (m.matches()) System.out.println(
       m.group(1) + ";" + m.group(2) + ";" + m.group(3));
    else System.out.println("No match");
  }
}

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