У меня проблема с Regex в Java для Android. я хотел бы получить первую операцию (и каждую подоперацию), как в следующих примерах:
- "OPERATION (ASYNC_OPERATION, _RFID_ITEM_SERIAL);"
- "OPERATION (CONCAT, ~1261,01, OPERATION (ASYNC_OPERATION, _RFID_ITEM_ID) ;, 21, OPERATION (ASYNC_OPERATION, _RFID_ITEM_SERIAL);); "
Как вы можете видеть, каждая операция может иметь подоперации ... И вот где яУ меня проблемы.
На самом деле я использую это регулярное выражение: ^\s*(OPERATION\s*\(\s*)(.*)(\);)
, но индекс ");"return всегда является последним индексом, и в случае двух подопераций внутри операции «Main» это неверно ...
private static Pattern operationPattern=Pattern.compile("^\\s*(OPERATION\\s*\\(\\s*)(.*)(\\);)",Pattern.CASE_INSENSITIVE);
public Operation(String text){
parseOperationText(text);
}
private void parseOperationText(String text){
String strText = text.replace("#,", "§");
Matcher matcher=operationPattern.matcher(strText);
if(matcher.find()) {
//This is an OPERATION
subOperations=new ArrayList<>();
String strChain = matcher.group(2);//Should only contain the text between "OPERATION(" and ");"
int commaIdx = strChain.indexOf(",");
if (commaIdx == -1) {
//Operation without parameter
operationType = strChain;
} else {
//Operation with parameters
operationType = strChain.substring(0, commaIdx);
strChain = strChain.substring(commaIdx + 1);
while (strChain.length()>0) {
matcher = operationPattern.matcher(strChain);
if (matcher.find()) {
String subOpText=matcher.group(0);
strChain=StringUtils.stripStart(strChain.substring(matcher.end())," ");
if(strChain.startsWith(",")){
strChain=strChain.substring(1);
}
subOperations.add(new Operation(subOpText));
}
else{
commaIdx = strChain.indexOf(",");
if(commaIdx==-1)
{
subOperations.add(new Operation(strChain));
strChain="";
}
else{
subOperations.add(new Operation(strChain.substring(0,commaIdx)));
strChain=strChain.substring(commaIdx+1);
}
}
}
}
}
else {
//Not an operation
//...
}
}
Это работает для образца 1, но для образца 2, после нахожденияОперация «Main» (в примере CONCAT), второе совпадение возвращает следующее:
OPERATION (ASYNC_OPERATION, _RFID_ITEM_ID) ;, 21, OPERATION (ASYNC_OPERATION, _RFID_ITEM_SERIAL);
Что бы я хотелкак получить это:
- "CONCAT, ~ 1261,01, OPERATION (ASYNC_OPERATION, _RFID_ITEM_ID) ;, 21, OPERATION (ASYNC_OPERATION, _RFID_ITEM_SERIAL);"
- "ASYNC_RFID_ITEM_ID "
- " ASYNC_OPERATION, _RFID_ITEM_SERIAL "