- 以下の値を持つ文字列があります。そこから関数名を取得する必要があります。関数名は動的です。
以下のコードを使用すると、「関数」という単語が何回発生したかを取得できます。関数名を取得する方法がわかりません。
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 に答える
私があなたの質問を正しく理解していれば、文字列 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()
これがあなたの質問に答えることを願っています。
@ボビーレイチェル。申し訳ありませんが、私はあなたの質問を理解していませんでした. ただし、名前を取得したい場合は、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(String loginId) // 取得するパーの名前を入力します
ユーザーIDの値を取得する別の関数
public String serachIn(String searchNode) { try {
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;
}
役立つことを願っています
を使用してこれを実現できます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));
}
出力:
[hello(), here()]
function hello() {print("another function test()")}
次のような入力が出力されるため、このコードは信頼できないことに注意してください。[hello(), test()]