在 Java 中使用正则表达式获取特殊字符之间的字符串

Get string between special characters using regex in Java

我正在尝试为输入字符串获取“@function”和“@”之间的字符串:

inputText = "@function square @default 2 @type Int @brief squares default number"

要获取“@function”和“@”之间的文本,正则表达式应该是什么?

为了满足以下条件(在 Java 中):

Pattern p = Pattern.compile( some magic regex expression... );
Matcher m = p.matcher(inputText);
functionName = m.group;
System.out.println(functionName);

打印"square"

正则表达式:

@function(.*?)@

这应该将 "square" 放入第一个捕获组。然后,您可以使用 Matcher.group(int) 来获取该组。如以下代码所示:

functionName = m.group(1);

group(int group) Returns the input subsequence captured by the given group during the previous match operation.

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)

编辑

向 trim 空格添加了“\s”

https://regex101.com/r/PH54FV/1