TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- import java.util.regex.*;
复制代码 /**
* <p>Title: 正则表达式简单应用</p>
* <p>Description: 利用正则表达式从一个javascript函数中提取函数名</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author 稽姬
* @version 1.0
*/
- public class GetFunctionName {
- /**
- * 得到js函数名的方法
- * @param functionContent String js函数内容字符串
- * @return String 返回的函数名字符串
- * @throws Exception 抛出的异常
- */
- static public String getFunctionName(String functionContent) throws Exception {
- String functionHead = "function([ ]|
| - | )+\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, "( |
- | |
|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
- aasdfdasfsdf(dsd,sdfs,sfda) {sadfdsaf;}";
- System.out.println(getFunctionName(ss));
- }
- }
复制代码 程序运行结果: C:java>java GetFunctionName
aasdfdasfsdf
源码下载:http://file.javaxxz.com/2014/11/1/000125000.zip |
|