gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:26:18 26 4
gpt4 key购买 nike

我正在尝试获取输入字符串的“@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);

打印“正方形”

最佳答案

正则表达式:

@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)

编辑

添加“\s”以修剪空格

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

关于java - 在Java中使用正则表达式获取特殊字符之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com