2013-10-03 32 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()]

相關問題