订阅所有JSP/Servlet的日志 订阅 | 这是最新一篇日志 上一篇 | 下一篇日志 下一篇 ]
learn

Java正则表达式初学者指南(转)

本文将介绍如何在Java中使用正则表达式来处理文本数据。正则表达式就是一个字符串,但和普通的字符串不同的是,正则表达式是对一组相似字符串的抽象,如下面的几个字符串:

a98b c0912d c10b a12345678d ab

我们仔细分析上面五个字符串,可以看出它们有一个共同特征,就是第一个字符必须是'a'或'c',最后一个字符必须是'b'或'd',而中间的字符是任意多个数字组成(包括0个数字)。因此,我们可以将这五个字符串的共同特点抽象出来,这就产生了一个正则表达式:[ac]\\d*[bd]。而根据这个正则表达式,我们可以写出无穷多个满足条件的字符串。

在Java中使用正则表达式的方法非常多,最简单的就是和字符串一起使用。在String中有四个方法可以使用正则表达式,它们是matches、split、replaceAll和replaceFirst。

一、matches方法

matches方法可以判断当前的字符串是否匹配给定的正则表达式。如果匹配,返回true,否则,返回false。matches方法的定义如下:

public boolean matches(String regex)

如上面给出的正则表达式我们可以用如下程序验证。
1
2
3
String[] ss = new String[]{"a98b", "c0912d",  "c10b",  "a12345678d",  "ab"};
for(String s: ss)
    System.out.println(s.matches("[ac]\\d*[bd]"));

输出结果:

true
true
true
true
true

下面简单解释一下这个正则表达式的含义。如果我们学过编译原理的词法分析,就会很容易理解上面的正则表达式(因为正则表达式的表示方法和词法分析中的表达式类似)。如在 [...]中的相当于或"|",如[abcd]相当于a|b|c|d,也就是a或b或c或d。如上面的正则表达式的开头部分是[ac],就代表着字符串的开头只能是a或c。[bd]表达字符串结尾只能是b或d。而中间的\d表达0-9的数字,由于\在正则表达式中有特殊含义,所以用\\来表示\。而*表示有0或无穷多个(这在词法分析中叫*闭包),由于*跟在\d后面,因此表达有0或无穷多个数字。

二、split方法

split方法使用正则表达式来分割字符串,并以String数组的形式返回分割结果。split有两种重载形式,它们定义如下:

public String[] split(String regex)
public String[] split(String regex, int limit)
如下面的代码将使用split的第一种重载形式来分割HTTP请求头的第一行,代码如下:
1
2
3
4
5
 
String s = "GET /index.html HTTP/1.1";
String ss[] = s.split(" +");
for(String str: ss)
System.out.println(str);

输出结果:
GET
/index.html
HTTP/1.1

在使用split的第一种重载形式时应注意,如果分割后的字符串最后有空串,将被忽略。如使用正则表达式\d来分割字符串a0b1c3456时,得到的数组的长度为3,而不是7。
在split的第二种重载形式中有一个limit参数,要分三种情况讨论:

1. 大于0: 如limit的值为n,那么将对正则表达式使用n-1次,下面的代码:
1
2
3
4
String s = "a0b1c3456";
String ss[] = s.split("\\d", 3);
for(String str: ss)
    System.out.println(str);

输出结果:

a
b
c3456

从输出结果可以看出,程序只对" a0b1c3456"使用了两次正则表达式,也就是在少扫描完字符'1'后,不管后面有没有满足条件的字符串,都将后面的字符串作为一个整体来作为返回数组的最后一个值。

2. 小于0: 不忽略结尾的空串。也就是上面的例子返回数组的长度应该是7,而不是3。
3. 等于0:这是默认值,相当于split的第一种重载形式。


三、replaceAll 和 replaceFirst方法

为两个方法的定义如下:
public String replaceAll(String regex, String replacement)
public String replaceFirst(String regex, String replacement)

这两个方法用replacement替换当前字符串中和regex匹配的字符串。使用方法很简单,这里不再详述,感兴趣的读者可以参考相关的文档。

对于Java中正则表达式的详细内容,请参考JDK文档。

平均得分
(0 次评分)





文章来自: blogjava
标签:
评论: 5 | 查看次数: 431
  • 共有 5 条评论
游客 [2008-11-07 11:25:59]
cheap wow power leveling Beyond knowing your limitations. HDRO gold it's important to be able to size up opponents lecteur mp3 at a glance. level wow Knowing their class is the first step, understanding. lord of rings online gold your places in a rock-paper-scissors scenario. lotro gold More important, however, is the estimation .lotro gold of gear. mp3 As much as skill and class
balance . mp3 mp4 player plays a part in the outcome . mp3 mp4 player of combat, gear is a major differentiator that makes up for shortcomings in other areas. mp3 mp4 player In fact, with . mp3 player kaufen the introduction of Resilience, gear more than mp4 ever plays a more substantial part in PvP. power level In an Arena match, the very first thing we . power level scope out is gear. wow level Through quick tab-selection viewing .wow leveling of character portraits, we generally wow lvl have a good idea of the classes we're up against if they keep their helm graphic on. wow lvl If they are wearing Season 3 shoulders, then we know . wow lvl 60 their relative experience. wow lvl 70 This is why the visual i.wow power leveling mpact of Arena shoulders is so important.wow powerlevel It immediately gives you a general idea of how tough the match will be. wow powerlevel Players in full S3 will likely have over 10k hp and over. wow powerleveling 400 Resilience, depending on the class and spec. A full S3 SL/SL Warlock, for example, will easily have. about 12-13k hp and over 400 Resilience. Identifying weapons is slightly more . difficult but will also give a general idea of an enemy's strength. Season 1 and 2 weapons share the same graphics, so it's harder to identify. Season 3 weapons, on the other hand, are distinctive and share models with Black Temple and Mount Hyjal weapons. which 最新免费网络游戏 have relatively the same power. A review of Brutal Gladiator weapons will come in handy because these will be the most common way to identify opponents of relative skill. With the new mechanics. in place for Arenas, Season 4 will more or less weed out the chaff from the grain.
游客 [2008-11-07 11:23:55]
mp3 8GB MP3 PLAYER A couple of people . apple ipod have posted about the Shattered Sun Peacekeepers slacking off on their jobs lately. buy cheap wow gold quite possibly thanks . canon digital camera to something Blizzard fed them . cheap world of warcraft gold in PatchIn their reports, they complain about Peacekeepers. digital camera attacking them for no reason, sometimes not even in retaliation for attacking (or defending yourself against). digital cameras a member of the opposing faction. dvd player I can actually empathize with this as. eve isk I encountered the ill-placed wrath of the Peacekeepers myself when I rezzed my wife's toon in front of . ipod the Staging Area. ipod nano Without having done anything other. ipod shuffle than rezz, the Peacekeepers promptly charged . ipod touch and made short work of me. ipods In my experience, I have found 网游 that the Peacekeepers around . mp3 the Shattered Sun Staging Area have . mp3 player been slacking off. mp3 players In fact, my wife's toon was ganked right in front . mp4 of the building and the so-called Peacekeepers . portable dvd players did absolutely nothing. world of warcraft buy gold Sensing a bug, my wife . wow wrote a ticket and got a somewhat rude e-mail response saying that -- you guessed it -- it was working as intended. wow gold An Alliance . wow gold guild on my server seemed to be aware of the fact and exploited it to full effect, killing solo players who could seek no refuge under the apathetic -- or even hostile -- Peacekeepers. wow leveling According to reports, it's a known bug -- one player even . wow powerleveling made a video to document it -- but so far Blizzard . zubehoer mp3 player has turned a blind eye to it. I got a more sympathetic response 网络游戏 from my GM who at least. mentioned he'd look into the situation. An in-game GM even reset the Peacekeepers in order to see if it would change anything (it didn't). I don't mind gankage




4GB MP3 PLAYER My wife is a shrewd little fox. Bluetooth Headset She knows just how much I love the fact. Bluetooth Headsets that she plays the game with me so sometimes, when we have our little domestic arguments, she makes sure. cell phone accessories to cancel her WoW account just to drive home a point. des po wow Of course, it doesn't mean much since we're both paid up for the next few months, but the message is clear -- "we make up (or you see things my way). digital camcorder or I'm quitting the game!" Of course, we don't reconcile merely because I'll be losing my . digital camcorders favorite playing partner, but I have to confess that it doesn't make . dvd players me happy one bit. free online games For parents, World of Warcraft can be a . free online war games useful bargaining chip for their kids with the parental . gold wow controls feature. gold wow It's easy enough to control WoW time if kids aren't doing their homework, floundering in school, or simply not. mp3 mp4 player doing their chores. mp3 player Conversely, a friend . mp3 player accessories of mine gave his son a WoW subscription when . mp3 player accessory he did well in school. mp3 player kaufen World of Warcraft can be so. online games much fun and addicting that it's . play war games often used as a social tool, and it's often upsetting when our. po wow friends quit playing the game. portable dvd player How many of us have . wow europe had friends whose significant others have "allowed" them to. wow geld play the game after, say, a wonderful date. wow gold verkaufen I'm not sure if it only applies to me, but . wow level service because I play the game with many of my RL friends . wow leveling service and my family, I use the lure of WoW . to full effect. I once had my brother do a specific task for . the promise of an upgrade to The Burning Crusade. A little before he finished what I asked him to do, I secretly upgraded his account. so he could免费网络游戏 finally make his Blood Elf Priest. Kind of manipulative, I know, but we did end up having . a lot of fun leveling our alts together. How about you. How much a part of your life is WoW and has it .最新网游 ever been used as a bargaining . chip in your social life.
游客 [2008-11-07 11:21:30]
2GB MP3 PLAYER Remember the WoW account hacking. 4GB MP3 PLAYER If you're a WoW player. buy wow gold you couldn't have missed . buying gold world of warcraft any of the articles posting this issue. cell phones Well, as it turns out, an article posted by . phones cell grimwell says that someone might have found the problem behind all the . cheap cell phones account hacking, stealing and selling even 5 year's worth items. cheap wow gold A piece of the BBC news article says:"Analysis [. cheap wow gold cheap wow gold cheapest wow gold ] showed that. eve isk it lay dormant on a victims . mp3 players machine until . portable mp3 player they ran World of Warcraft (WoW) at which point it captured login data and sent it to. portable mp3 players the hacking group. sell wow gold The group's enthusiastic use of the cursor flaw suggests it is trying to . world of warcraft gold do the same again. wow The online fantasy game . wow gold now has more than eight million active players around the world. wow gold Research by security firm Symantec . wow gold suggests that the raw value of a WoW account is now higher. wow gold than a credit card and its associated verification data. wow gold "Normally, as a WoW player, you'd know about the risks involved when creating an online account, yet some were . wow gold lazy enough not to check on their accounts every once in a while, thus resulting in their items . wow gold kaufen and WoW currency being stolen. wow gold kaufen Everyone knows that . stuff like that happen, some. even managed to hack the Superbowl website and use it . to host code for spyware, so monitor the hell out of your computer!In an article I wrote yesterday. about hackers seeing 游戏 console users as the new target, there is a comment 魔兽 coming from Stefana Muller.
游客 [2008-10-28 15:49:20]
Buy Lotro Gold | Lord Of The Rings Online Gold
Lotro Accounts
| Buy Lotro Accounts
Lord Of The Rings Online Power Leveling | Lord Of The Rings Online PowerLeveling
Lotro Cd Key | Lord Time Card
Lotro Gold | Lotro Gold Instant Delivery
lord of the rings online accounts | lord of the rings online accounts for sale
Lotro Power Leveling | Lotro Powerleveling
Lord Of The Rings Online Cd Key | Lord Of The Rings Online Time Card
Lord of the Rings Online Gold
Buy Lotro Gold
Sell LoTRO Gold
LoTRO CD Key
LoTRO Europe Gold
Cheap LoTRO Accounts
Lord of the Rings Online Power Leveling
Lord of the Rings online CD Key
Cheap Lotro Gold
Air Jordan Shoes
Warhammer Gold
Warhammer Online Gold
Warhammer Accounts
Warhammer Power Leveling
Warhammer Online Key
Warhammer Gold
Warhammer Online Gold
Warhammer Time Card
Warhammer CD Key
WAR gold
warhammer online gold
Buy WAR gold
Buy warhammer gold
Buy warhammer online gold
warhammer gold
WAR Accounts
warhammer Accounts
warhammer online Accounts
Buy WAR Accounts
warhammer Accounts for sale
Warhammer Power Leveling
Warhammer Online Power Leveling
War Power Leveling
Buy Warhammer Power Leveling
Warhammer PowerLeveling
Cheap Warhammer Power Leveling
Cheap Warhammer Online Power Leveling
Buy War Power Leveling
Warhammer EU Power Leveling
Cheap Warhammer Gold
Cheap Warhammer online gold
Buy Cheap Warhammer Gold
Buy WAR Gold
Warhammer EU Gold
Warhammer EU Power Leveling
Warhammer EU CD Key
Warhammer EU Accounts
Warhammer CD Key
Warhammer online CD Key
Warhammer Timecard
Buy Warhammer Time Card
Warhammer 60 days Time Card
Cheap WAR Accounts
Cheap warhammer Accounts
Cheap warhammer online Accounts
Buy Cheap WAR Accounts
buy Warhammer CD Key
buy Warhammer online CD Key
cheap Warhammer CD key
warhammer time card
Warhammer prepaid time card
游客 [2008-10-16 11:04:27]
  • 共有 5 条评论
发表评论
昵 称:  登录
内 容:
选 项:
字数限制 1000 字 | UBB代码 开启 | [img]标签 开启