简体   繁体   English

从背面搜索时如何从一部分字符串中获取子字符串

[英]How to get substring from a part of string while searching from the back

I have a string with code from another JAVA class and i am extracting Doc comments. 我有一个包含来自另一个JAVA类的代码的字符串,并且正在提取Doc注释。 I have a string with the following content: 我有一个包含以下内容的字符串:

"public static String[] scanread() throws Exception{"

I need to get the "scanread()" how can i extract that? 我需要获取“ scanread()”,我该如何提取呢? I was hoping something that looks for ")" and continues reading right to left until it reaches white space, then extracts it. 我希望找到“)”的东西,并继续从右到左阅读,直到到达空白处,然后将其提取出来。 I am not too sure how would i do that. 我不太确定我该怎么做。 Also with this i am worried if there is a space between "scanread" and "()" that might not work. 与此同时,我担心“ scanread”和“()”之间是否有可能不起作用的空间。

Any help would be awesome. 任何帮助都是极好的。

Thanks 谢谢

Use the below regex along with Pattern and Matcher classes. 将以下正则表达式与Pattern和Matcher类一起使用。

"\\S+\\)"

OR 要么

"\\S+\\s*\\(\\)"

\\S+ matches one or more non-space characters , so this matches all the non-space characters which exists before to ) bracket, including the bracket. \\S+匹配一个或多个非空格字符,因此它匹配到( )括号之前的所有非空格字符,包括括号。

DEMO DEMO

String s = "public static String[] scanread() throws Exception{";
Matcher m = Pattern.compile("\\S+\\)").matcher(s);
while(m.find()){
System.out.println(m.group());
}

Output: 输出:

scanread()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM