请问JAVA中正则表达式匹配怎么实现的!

作者&投稿:彩章 (若有异议请与网页底部的电邮联系)
请问怎么用java正则表达式提取以下文本中指定的内容~

正则表达式是根据规则来匹配文本,你这里只给了一个文本示例,所以无法建立其比较普遍通用的规则。
以下是示例代码,可供参考。代码中对每一个你要的数据进行了一个单独匹配,也可以通过一次匹配取出全部的数据。
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Test { public static void main(String[] args) { Pattern zj = Pattern.compile("地震震级为(.*?级)"); Pattern sd = Pattern.compile("震源深度(.*?米)"); Pattern fw = Pattern.compile("倒塌房屋(.*?间)"); Pattern sw = Pattern.compile("(\\d+人).*?死亡"); String content = "截至2017年日3月7日,记者从前线传来消息,此次地震震级为4.7级,震源深度8千米。国道213线K774+600m处发生塌方,预计倒塌房屋200余间,地震造成6人当场死亡,23人重伤,另有7辆车被砸毁。"; Matcher matcher = zj.matcher(content); if (matcher.find()) { String result = matcher.group(1); System.out.println("地震震级:" + result); } matcher = sd.matcher(content); if (matcher.find()) { String result = matcher.group(1); System.out.println("震源深度:" + result); } matcher = fw.matcher(content); if (matcher.find()) { String result = matcher.group(1); System.out.println("倒塌房屋:" + result); } matcher = sw.matcher(content); if (matcher.find()) { String result = matcher.group(1); System.out.println("死亡人数:" + result); } }}

你的左右没分清楚

如果不用正则表达式,就用int i = str.lastIndexOf("/n");能找出位置来

如果用正则表达式,就用"(/n)(?=(^/n)*)"意思就是匹配后面再没有/n的/n

Java中正则表达式匹配的语法规则:

以下是整理出来的Java下运用正则表达式实现匹配的程序案例,代码如下:

package org.luosijin.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式
 * @version V5.0
 * @author Admin
 * @date   2015-7-25
 */
public class Regex {

    /**
     * @param args
     * @author Admin
     * @date 2015-7-25
     */

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("b*g");
        Matcher matcher = pattern.matcher("bbg");
        System.out.println(matcher.matches());
        System.out.println(pattern.matches("b*g","bbg"));
        //验证邮政编码
        System.out.println(pattern.matches("[0-9]{6}", "200038"));
        System.out.println(pattern.matches("//d{6}", "200038"));
        //验证电话号码
        System.out.println(pattern.matches("[0-9]{3,4}//-?[0-9]+", "02178989799"));
        getDate("Nov 10,2009");
        charReplace();
        //验证身份证:判断一个字符串是不是身份证号码,即是否是15或18位数字。
        System.out.println(pattern.matches("^//d{15}|//d{18}$", "123456789009876"));
        getString("D:/dir1/test.txt");
        getChinese("welcome to china,江西奉新,welcome,你!");
        validateEmail("luosijin123@163.com");
    }
    /**
     * 日期提取:提取出月份来
     * @param str
     * @author Admin
     * @date 2015-7-25
     */
    public static void getDate(String str){
        String regEx="([a-zA-Z]+)|//s+[0-9]{1,2},//s*[0-9]{4}";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(str);
        if(!matcher.find()){
            System.out.println("日期格式错误!");
            return;
        }
        System.out.println(matcher.group(1));    //分组的索引值是从1开始的,所以取第一个分组的方法是m.group(1)而不是m.group(0)。
    }
    /**
     * 字符替换:本实例为将一个字符串中所有包含一个或多个连续的“a”的地方都替换成“A”。
     * 
     * @author Admin
     * @date 2015-7-25
     */
    public static void charReplace(){
        String regex = "a+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("okaaaa LetmeAseeaaa aa booa");
        String s = matcher.replaceAll("A");
        System.out.println(s);
    }
    /**
     * 字符串提取
     * @param str
     * @author Admin
     * @date 2015-7-25
     */
    public static void getString(String str){
        String regex = ".+/(.+)$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        if(!matcher.find()){
            System.out.println("文件路径格式不正确!");
            return;
        }
        System.out.println(matcher.group(1));
    }
    /**
     * 中文提取
     * @param str
     * @author Admin
     * @date 2015-7-25
     */
    public static void getChinese(String str){
        String regex = "[//u4E00-//u9FFF]+";//[//u4E00-//u9FFF]为汉字 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            sb.append(matcher.group());
        }
        System.out.println(sb);
    }
    /**
     * 验证Email
     * @param email
     * @author Admin
     * @date 2015-7-25
     */
    public static void validateEmail(String email){
        String regex = "[0-9a-zA-Z]+@[0-9a-zA-Z]+//.[0-9a-zA-Z]+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        if(matcher.matches()){
            System.out.println("这是合法的Email");
        }else{
            System.out.println("这是非法的Email");
        }
    }
}


java中正则表达式的匹配其实是利用不确定的有穷自动机(NFA)结合向上追溯的算法来实现的。
以下是示例代码:

import java.util.* ;

/*
* An NFAState is a node with a set of outgoing edges to other
* NFAStates.
*
* There are two kinds of edges:
*
* (1) Empty edges allow the NFA to transition to that state without
* consuming a character of input.
*
* (2) Character-labelled edges allow the NFA to transition to that
* state only by consuming the character on the label.
*
*/
class NFAState
{
/*
* WARNING:
*
* The maximum integer character code we'll match is 255, which
* is sufficient for the ASCII character set.
*
* If we were to use this on the Unicode character set, we'd get
* an array index out-of-bounds exception.
*
* A ``proper'' implementation of this would not use arrays but
* rather a dynamic data structure like Vector.
*/
public static final int MAX_CHAR = 255 ;

public boolean isFinal = false ;
private ArrayList<NFAState> onChar[] = new ArrayList[MAX_CHAR] ;
private ArrayList<NFAState> onEmpty = new ArrayList() ;

/*
* Add a transition edge from this state to next which consumes
* the character c.
*/
public void addCharEdge(char c, NFAState next) {
onChar[(int)c].add(next) ;
}

/*
* Add a transition edge from this state to next that does not
* consume a character.
*/
public void addEmptyEdge(NFAState next) {
onEmpty.add(next) ;
}

public NFAState () {
for (int i = 0; i < onChar.length; i++)
onChar[i] = new ArrayList() ;
}

public boolean matches(String s) {
return matches(s,new ArrayList()) ;
}

private boolean matches(String s, ArrayList visited) {
/*
* When matching, we work character by character.
*
* If we're out of characters in the string, we'll check to
* see if this state if final, or if we can get to a final
* state from here through empty edges.
*
* If we're not out of characters, we'll try to consume a
* character and then match what's left of the string.
*
* If that fails, we'll ask if empty-edge neighbors can match
* the entire string.
*
* If that fails, the match fails.
*
* Note: Because we could have a circular loop of empty
* transitions, we'll have to keep track of the states we
* visited through empty transitions so we don't end up
* looping forever.
*/

if (visited.contains(this))
/* We've found a path back to ourself through empty edges;
* stop or we'll go into an infinite loop. */
return false ;

/* In case we make an empty transition, we need to add this
* state to the visited list. */
visited.add(this) ;

if (s.length() == 0) {
/* The string is empty, so we match this string only if
* this state is a final state, or we can reach a final
* state without consuming any input. */
if (isFinal)
return true ;

/* Since this state is not final, we'll ask if any
* neighboring states that we can reach on empty edges can
* match the empty string. */
for (NFAState next : onEmpty) {
if (next.matches("",visited))
return true ;
}
return false ;
} else {
/* In this case, the string is not empty, so we'll pull
* the first character off and check to see if our
* neighbors for that character can match the remainder of
* the string. */

int c = (int)s.charAt(0) ;

for (NFAState next : onChar[c]) {
if (next.matches(s.substring(1)))
return true ;
}

/* It looks like we weren't able to match the string by
* consuming a character, so we'll ask our
* empty-transition neighbors if they can match the entire
* string. */
for (NFAState next : onEmpty) {
if (next.matches(s,visited))
return true ;
}
return false ;
}
}
}

/*
* Here, an NFA is represented by an entry state and an exit state.
*
* Any NFA can be represented by an NFA with a single exit state by
* creating a special exit state, and then adding empty transitions
* from all final states to the special one.
*
*/
public class NFA
{
public NFAState entry ;
public NFAState exit ;

public NFA(NFAState entry, NFAState exit) {
this.entry = entry ;
this.exit = exit;
}

public boolean matches(String str) {
return entry.matches(str);
}

/*
* c() : Creates an NFA which just matches the character `c'.
*/
public static final NFA c(char c) {
NFAState entry = new NFAState() ;
NFAState exit = new NFAState() ;
exit.isFinal = true ;
entry.addCharEdge(c,exit) ;
return new NFA(entry,exit) ;
}

/*
* e() : Creates an NFA which matches the empty string.
*/
public static final NFA e() {
NFAState entry = new NFAState() ;
NFAState exit = new NFAState() ;
entry.addEmptyEdge(exit) ;
exit.isFinal = true ;
return new NFA(entry,exit) ;
}

/*
* rep() : Creates an NFA which matches zero or more repetitions
* of the given NFA.
*/
public static final NFA rep(NFA nfa) {
nfa.exit.addEmptyEdge(nfa.entry) ;
nfa.entry.addEmptyEdge(nfa.exit) ;
return nfa ;
}

/*
* s() : Creates an NFA that matches a sequence of the two
* provided NFAs.
*/
public static final NFA s(NFA first, NFA second) {
first.exit.isFinal = false ;
second.exit.isFinal = true ;
first.exit.addEmptyEdge(second.entry) ;
return new NFA(first.entry,second.exit) ;
}

/*
* or() : Creates an NFA that matches either provided NFA.
*/
public static final NFA or(NFA choice1, NFA choice2) {
choice1.exit.isFinal = false ;
choice2.exit.isFinal = false ;
NFAState entry = new NFAState() ;
NFAState exit = new NFAState() ;
exit.isFinal = true ;
entry.addEmptyEdge(choice1.entry) ;
entry.addEmptyEdge(choice2.entry) ;
choice1.exit.addEmptyEdge(exit) ;
choice2.exit.addEmptyEdge(exit) ;
return new NFA(entry,exit) ;
}

/* Syntactic sugar. */
public static final NFA re(Object o) {
if (o instanceof NFA)
return (NFA)o ;
else if (o instanceof Character)
return c((Character)o) ;
else if (o instanceof String)
return fromString((String)o) ;
else {
throw new RuntimeException("bad regexp") ;
}
}

public static final NFA or(Object... rexps) {
NFA exp = rexps[0] ;
for (int i = 1; i < rexps.length; i++) {
exp = or(exp,re(rexps[i])) ;
}
return exp ;
}

public static final NFA s(Object... rexps) {
NFA exp = e() ;
for (int i = 0; i < rexps.length; i++) {
exp = s(exp,re(rexps[i])) ;
}
return exp ;
}

public static final NFA fromString(String str) {
if (str.length() == 0)
return e() ;
else
return s(re(str.charAt(0)),fromString(str.substring(1))) ;
}

public static void main(String[] args) {
NFA pat = s(rep(or("foo","bar")),"") ;
String[] strings =
{ "foo" , "bar" ,
"foobar", "farboo", "boofar" , "barfoo" ,
"foofoobarfooX" ,
"foofoobarfoo" ,
} ;
for (String s : strings) {
System.out.println(s + "\t:\t" +pat.matches(s)) ;
}
}
}

详细参考:http://matt.might.net/articles/implementation-of-nfas-and-regular-expressions-in-java/

正则表达式是匹配响应的字符串,但这个字符串可能比较复杂,用一般的表达可能不是很清晰,简单点说就是正则表达式表达的东西无二义性,
从你的:
String s=new String("0.0.0.0 0.255.255.255 CHINA 中国1");
来看,你只要用简单的:
String s1 = s.replaceFirst("255 ","255,");就可以解决问题啊!
为什么要用正则呢?
如果想用,可以参考我写的IPV4匹配规则:

IPV4地址匹配,可以检查每个段在0-255,可以检测非法IP

测试数据:
192.168.1.1,
135.0.0.0,
1.1.1.1
178.153.558,259
12.12.12.12
1023.2562.12.10,
14.15.213.2555
正则表达式:
((2[0-5][0-5]|1\d\d|\d\d|\d)\.){3}(2[0-5][0-5]|1\d\d|\d\d|\d)
匹配结果:
127.0.0.1,
192.168.1.1,
135.0.0.0,
1.1.1.1
12.12.12.12

String subjectString=new String("0.0.0.0 0.255.255.255 CHINA 中国1");
String resultString = null;
try {
Pattern regex = Pattern.compile("(\\d) ");
Matcher regexMatcher = regex.matcher(subjectString);
try {
resultString = regexMatcher.replaceAll("$1,");
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}


Java中怎么用正则表达式来表示小数 比如:3.14怎么用正则表达式来表示...
24 备注:这就是最终结果了,别忘了"+"可以用"*"替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里 25 xml文件:^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\\\.[x|X][m|M][l|L]26 中文字符的正则表达式:[\一-\龥]...

求教java中正则表达式问题
split返回一个数组数 -1 = 多少个B

java正则表达式 ^\/.*\\\\.do$ 和 ^\/.*\\\\.[-\\\\w]+$ 各表示匹配什么东西呀...
^\/.*\\\\.do$ 表示匹配一个以“\/”开头,“do”结尾,中间必须出现一个“\\”,而开头的"\/"和中间的“\\”中间可以有任意的字符0个或者多个,且中间的“\\”和结尾的“do”之间必须要以个字符

java 正则表达式 (.+?)怎样理解?举个例子详细说明。
正则表达式的符号理解吗,* ? + 其中*代表的是0-无穷个个,比如\/^w*$\/,代表有0个或多个数字或字母 ?代表是0-1个,比如\/^d*$\/,代表最多只有一个数字,也可能没有 +代表有1-无穷个,比如\/^d+$\/,代表最少有一个数字 .代表的是换行符之外的任意字符,它代表的字符,不是个数...

java正则表达式中.*代表什么意思
src=".*"匹配结果是:src="test.jpg" width="60px" height="80px"意思是从="往后匹配,直到最后一个"匹配结束 懒惰模式正则:src=".*?"结果:src="test.jpg"因为匹配到第一个"就结束了一次匹配。不会继续向后匹配。因为他懒惰嘛。.表示除\\n之外的任意字符 表示匹配0-无穷 +表示匹配1-无穷...

.jpg 在java中用正则表达式如何表示呢
验证一年的12个月:"^(0?[1-9]|1[0-2])$"正确格式为:"01"~"09"和"1"~"12"。验证一个月的31天:"^((0?[1-9])|((1|2)[0-9])|30|31)$"正确格式为;"01"~"09"和"1"~"31"。匹配中文字符的正则表达式: [\一-\龥]匹配双字节字符(包括汉字在内):[^\\x00-\\...

在Java中,用正则表达式"\/\/D+"分割
public static void main(String[] args) { String str = "{1,4},{0,6},{3,5},{5,7},{3,8},{5,9},{6,10},{8,11},{8,12},{2,13},{12,14}";String reg = "\\\\d+";Pattern pattern = Pattern.compile(reg);Matcher matcher = pattern.matcher(str);ArrayList<Integer> ...

关于java的正则表达
\/eg*\/ 因为上述正则表达式中包含“*”元字符,表示可以与目标对象中的 “easy”, “ego”, 或者 “egg”等在字母e后面连续出现零个或多个字母g的字符串相匹配。 \/Wil?\/ 因为上述正则表达式中包含“?”元字符,表示可以与目标对象中的 “Win”, 或者“Wilson”,等在字母i后面连续出现零个或一个字母l的字符...

java中如何用正则表达式判断一个字符串中是否包含0-9的数字?
\/\/ 判断一个字符串是否都为数字 public boolean isDigit(String strNum) { return strNum.matches("[0-9]{1,}");} \/\/ 判断一个字符串是否都为数字 public boolean isDigit(String strNum) { Pattern pattern = Pattern.compile("[0-9]{1,}");Matcher matcher = pattern.matcher((Char...

java正则表达式语法中的标签是什么呢?是类似\\\\S,\\\\d这样的东西吗?_百 ...
标签是什么,在我的理解里;标签是一个功能实现的最小单位工具;比如html里的一系列标签,功能具体化就是标签 那在java正则表达式语法中的标签是什么呢?各种各样样的定义就是标签,它们组合起来就是正则表达式;举个例子,字符类 [abc] a、b 或 c(简单类)[^abc] 任何字符,除了 a、b 或 c(...

吴川市15813687804: java 怎么用正则表达式拿出一篇文章中匹配 -
鲍世降纤: 利用正则表达式从给定的字符串中取出符合匹配规则的字符串的Java程序如下:import java.util.regex.Matcher;import java.util.regex.Pattern;public class E { public static void main(String[] args) { Pattern p = Pattern.compile("[A-Za-z]+");//设定匹...

吴川市15813687804: java 怎么利用正则表达式从给定的字符串中取出匹配规则字符串 -
鲍世降纤: string teststring = "java怎么利用正则表达式从给定的字符串中取出匹配规则字符串"; pattern pattern = pattern.compile("\\w+"); matcher matcher = pattern.matcher(teststring); while(matcher.find()) { system.out.println(matcher.group()); }

吴川市15813687804: 请问JAVA中正则表达式匹配怎么实现的!
鲍世降纤: String subjectString=new String("0.0.0.0 0.255.255.255 CHINA 中国1");String resultString = null;try { Pattern regex = Pattern.compile("(\\d) "); Matcher regexMatcher = regex.matcher(subjectString); try { resultString = regexMatcher.replaceAll("...

吴川市15813687804: 怎样用java的正则表达式匹配这样的网址 -
鲍世降纤: Java中正则表达式匹配的语法规则:以下是整理出来的Java下运用正则表达式实现匹配的程序案例,代码如下:package org.luosijin.test;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * 正则表达式 * @version V5.0 * @author ...

吴川市15813687804: 请问java字符串处理的正则表达式中,要怎么匹配//...和/*...*/(也就是匹配java注释)? 谢谢! -
鲍世降纤: 下面是关于java的正则处理 原理和上面的基本一样, 我觉得如果真的匹配java代码里面的注释这个还不够 还需要很多的条件 因为有可能你的代码里面本身就有相关字符的处理.所以我认为需要根据你具体的情景进行正则设计Pattern p=Pattern...

吴川市15813687804: 用JAVA语言编写正则表达式匹配指定的汉字的方法 -
鲍世降纤: 匹配中文字符的正则表达式: [\u4e00-\u9fa5] 匹配双字节字符(包括汉字在内):[^\x00-\xff] 匹配空行的正则表达式:\n[\s ¦ ]*\r 匹配HTML标记的正则表达式:/ <(.*)> .* <\/\1> ¦ <(.*) \/> / 匹配首尾空格的正则表达式:(^\s*) ¦(\s*$) 用正...

吴川市15813687804: java正则表达式从右到左匹配怎么实现 -
鲍世降纤: 你的左右没分清楚 如果不用正则表达式,就用int i = str.lastIndexOf("/n");能找出位置来 如果用正则表达式,就用"(/n)(?=(^/n)*)"意思就是匹配后面再没有/n的/n

吴川市15813687804: java正则表达式 如何全局匹配 -
鲍世降纤: 楼上有个说的很对,用while(m.find()).....具体就是: while(m.find()) { // 处理 String string = m.group(); }// while中的find,是进行一次搜索,发现后即找到aab,进行循环体中处理,,然后再从上次找的的地方继续向后find.........直到结束

吴川市15813687804: JAVA里,如何匹配一个多位数?(正则表达式) -
鲍世降纤: import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Second { public static void main( String[] args ) { String regex = "[0-9]{1,}"; String str = " 33 444 5555"; Pattern pat = Pattern.compile(regex);Matcher matcher = pat....

吴川市15813687804: java 正则表达式用法 -
鲍世降纤: 先回答楼主的正则表达式吧一个是建表语句格式如下 : create【空格若干】table 【表名和其他信息】 正则表达式如下:create\s+table\s+.+第二个是建索引语句格式如下 : create【空格和字母若干】index【空格和字母下划线等若干】 正则表...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网