当前页面: 开发资料首页 → Java 专题 → 利用正则表达式从一个javascript函数中提取函数名
摘要: 利用正则表达式从一个javascript函数中提取函数名
import java.util.regex.*;
/**
*
Title: 正则表达式简单应用
Description: 利用正则表达式从一个javascript函数中提取函数名
Copyright: Copyright (c) 2005
Company:
public class GetFunctionName {
/**
* 得到js函数名的方法
* @param functionContent String js函数内容字符串
* @return String 返回的函数名字符串
* @throws Exception 抛出的异常
*/
static public String getFunctionName(String functionContent) throws Exception {
String functionHead = "function([ ]|\r|\n|\t)+\\w+\\(";
String temp = getMatchString(functionContent, functionHead);
if (temp == null) {
throw new Exception("javascript函数定义错误!");
}
temp = deleteWhiteSpaceAndNewLine(temp);
temp = temp.substring(8);
temp = temp.substring(0, temp.length() - 1).trim();
return temp;
}
/**
* 从一个字符串中取出需要的字符串的方法
* @param originalString String 原串
* @param pattern String 要取得的字符串的正则表达式
* @return String 返回的结果
*/
static public String getMatchString(String originalString, String pattern) {
String temp = null;
Pattern p = null;
Matcher m = null;
p = Pattern.compile(pattern);
m = p.matcher(originalString);
if (m.find()) {
temp = m.group();
}
return temp;
}
/**
* 去掉一个字符串中所有的空白的方法
* @param originalString String 原串
* @return String 返回的结果
* @throws Exception 抛出的异常
*/
static public String deleteWhiteSpaceAndNewLine(String originalString) throws
Exception {
if (originalString == null) {
throw new Exception("deleteWhiteSpaceAndNewLine时字符串为空");
}
return replace(originalString, "(\t|\n| |\r|\f)", "");
}
/**
* 将原串中的指定内容替换为新内容的方法
* @param originalString String 原串
* @param pattern String 指定内容
* @param replaceString String 新内容
* @return String 返回的结果
*/
static public String replace(String originalString, String pattern,
String replaceString) {
String newString = null;
Pattern p = null;
Matcher m = null;
p = Pattern.compile(pattern);
m = p.matcher(originalString);
newString = m.replaceAll(replaceString);
return newString;
}
/**
* 主方法用于测试
* @param args String[] 命令行数组参数
* @throws Exception 抛出的异常
*/
static public void main(String[] args) throws Exception {
String ss = "function \t\t\n aasdfdasfsdf(dsd,sdfs,sfda) {sadfdsaf;}";
System.out.println(getFunctionName(ss));
}
}
程序运行结果:
C:\java>java GetFunctionName
aasdfdasfsdf
</td> </tr> <tr>