gpt4 book ai didi

java - 返回第一个括号中出现的单词的正则表达式

转载 作者:行者123 更新时间:2023-12-01 19:21:50 25 4
gpt4 key购买 nike

示例:

  1. ((UINT32)((384UL*1024UL) - 1UL)) 应返回“UINT32”
  2. (char)abc 应返回“char”。
  3. ((int)xyz) 应返回“int”。

最佳答案

    Pattern p = Pattern.compile("\\(([^()]*)\\)");
String[] tests = {
"((UINT32)((384UL*1024UL) - 1UL))",
"(char)abc",
"((int)xyz)"
};

for (String s : tests) {
Matcher m = p.matcher(s);
if (m.find())
System.out.println(m.group(1));
}

打印

UINT32
char
int

正则表达式说明:

  • \\(( 开头
  • (开始捕获组
  • [^()]*() 之外的任何内容 0 次或多次
  • ) 结束捕获组
  • \\)) 结尾。
<小时/>

不过,使用正则表达式有点过分了。你也可以这样做

int close = s.indexOf(')');
int open = s.lastIndexOf('(', close);
result = s.substring(open+1, close);

关于java - 返回第一个括号中出现的单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3889913/

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