Java 8在这里。我有以下功能:
public String extractArgs(String function) {
Pattern inRegex = Pattern.compile("in\\(.*\\)");
Matcher inMatch = inRegex.matcher(function);
log("num in(...) function matches: " + inMatch.groupCount() + "but does inMatch.matches()? " + inMatch.matches());
if(inMatch.groupCount() > 0) {
return inMatch.group(1);
} else {
return "";
}
}
当我将"in(hello)"
作为参数传递时,我得到以下输出:
num in(...) function matches: 0 but does inMatch.matches()? true
我的理解是,如果inMatch.matches()
返回true
(正在发生),我应该至少有一个匹配组(inMatch.groupCount > 0
)。< / p>
我试图将输入的arg字符串与正则表达式进行比较,并且(如果匹配)获取&#34; in(...)
函数&#34;中包含的文本的模糊。因此,如果我调用extractArgs("in(hello)")
,那么它应该返回字符串"hello"
。我哪里出错了?!
答案 0 :(得分:2)
原始正则表达式中没有捕获组。要引入捕获组(您想要),您应该按照以下行定义正则表达式:
[FunctionName("FunctionSplitter")]
public static async Task PreProcessor(
[EventHubTrigger("%IoTHubName%", Connection = "connectionIoTHub", ConsumerGroup = "splitter")] EventData ed,
[EventHub("%EventHubName%", Connection = "connectionEventHub")] IAsyncCollector<EventData> outputEventHubMessages,
TraceWriter log)
{
log.Info($"IoT Hub trigger function processed an event {ed.SequenceNumber}");
// Create a clone
var edclone = ed.Clone();
edclone.PartitionKey = Convert.ToString(ed.Properties.ContainsKey("deviceGroupId") ? ed.Properties["deviceGroupId"] : "1234567890");
await outputEventHubMessages.AddAsync(edclone);
await outputEventHubMessages.FlushAsync();
}
请注意,我在参数所在的位置添加了 in\\((.*)\\)
括号。这样我就在()
周围创建了一个捕获组,因此您现在将拥有这些组:
.*