2013-10-03 34 views
0
  • 我有一个字符串,它具有下面的值。我需要从中获取函数名称。并且函数名称是动态的。
  • 使用下面的代码,我可以得到单词“功能”已经发生了多少次。不知道如何获取函数名称。使用java从另一个字符串获取特定字符串

    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()作为输出。

+3

什么是关于'function hello(){print(“hi from function hello”)}'? – kan

回答

0

@ Bobby rachel。对不起,我不明白你的问题。 但是如果你想检索名字,你可以使用XML格式。然后从中检索。

例如 String userid = request.getParameter(“part1”);

String stri = "req=<header><requesttype>LOGIN</requesttype></header>" 
      + "<loginId>" 
      + userid     //the string you get and want to retrieve       
      + "</loginId>"     //from this whole string 

object.searchIn(字符串登录ID)//输入名称齐名的要检索

另一个函数来获取用户ID

公共字符串serachIn(字符串searchNode)的值{ 尝试{

 int firstpos = stri.indexOf("<" + searchNode + ">"); 
     int endpos = stri.indexOf("</" + searchNode + ">"); 
     String nodeValue = stri.substring(firstpos + searchNode.length() + 2, endpos); 
     System.out.println("node value"+searchNode+nodeValue); 

     return nodeValue; 

    } 

我希望它能帮助

2

如果我已经理解了你的问题,你试着解析字符串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() 

我希望这回答了你的问题。

0

可以使用regex实现这一点,这里有一个例子:

public static List<String> extractFunctionsNames(String input) { 
    List<String> output = new ArrayList<String>(); 
    Pattern pattern = Pattern.compile("(function\\s+([^\\(\\)]+\\([^\\)]*\\)))+"); 
    Matcher matcher = pattern.matcher(input); 
    while (matcher.find()) { 
     output.add(matcher.group(2)); 
    } 
    return output; 
} 

public static void main(String[] args) { 
    String input = "function hello(){\n" 
        + " \n}" 
        + "\nfunction here(){\n" 
        + "}\n"; 
    System.out.println(extractFunctionsNames(input)); 
} 

OUTPUT:

[hello(), here()] 

请注意,此代码是不可靠的,因为function hello() {print("another function test()")}一个输入将输出[hello(), test()]

相关问题