gpt4 book ai didi

java - 使用java从另一个字符串中获取特定字符串

转载 作者:行者123 更新时间:2023-12-02 06:40:55 25 4
gpt4 key购买 nike

  • 我有一个具有以下值的字符串。我需要从中获取函数名称。并且函数名称是动态的。
  • 使用下面的代码我可以得到“function”这个词出现了多少次。不知道如何获取函数名称。

       String strLine=request.getParameter("part1");
    if(strLine!=null){
    String findStr = "function ";
    int lastIndex = 0;
    int count =0;
    while(lastIndex != -1){
    lastIndex = strLine.indexOf(findStr,lastIndex);
    if( lastIndex != -1){
    count ++;
    lastIndex+=findStr.length();
    }
    }
    System.out.println("count "+count);
    }
  • part1 是来自用户的值。这可以是,

           function hello(){
    }
    function here(){
    }
  • 在上面的事情中,没有更改任何函数和函数名称。

  • 我想获取 hello() 和 here() 作为输出。

最佳答案

如果我正确理解了你的问题,你会尝试解析字符串part1并且想要获取函数名称。它们是动态的,因此您不能对名称做出任何假设。在这种情况下,您要么必须编写自己的解析器,要么使用正则表达式。

以下程序使用正则表达式提取函数名称:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Stackoverflow {
private static Pattern pattern = Pattern.compile("\\s([a-zA-Z0-9_]+\\(\\))", Pattern.DOTALL | Pattern.MULTILINE);

public static void main(String[] args) {
String part1 = "function hello(){\n" +
" }\n" +
" function here(){\n" +
" }";
Matcher matcher = pattern.matcher(part1);
while (matcher.find()) {
String str = matcher.group();
System.out.println(str);
}
}
}

输出为:

hello()
here()

我希望这能回答您的问题。

关于java - 使用java从另一个字符串中获取特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154615/

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