打算每天花點時間把學習Java的過程記錄下來,這個斷斷續續的Java學習 筆記是自己學習java過程中的零星總結,以作備份。同時希望與CSharp轉Java領域的朋友們共同學習。
相比而言,C#是後生 ,它吸收了 Java的大部分精華,但兩者還是有一些細微差別,今天,我們看第一個區別:
■ 許多系統對象方法都有相同的方法名,只是在大小寫形式上有區別。
我們 通過一個最簡單的例子:
文本"1ASDF NI1221312 HK1 2222/1
1QWW NI1232133 HK1 3333/1"
兩行文本,比如第1行表示旅客1的信息,第2行表示旅客2的信息,後面可能還有很多旅客信息,如何用正則表達式提取每個旅客的信息?最後結果類似於 String1:1ASDF NI1221312 HK1 2222/1,String2:1QWW NI1232133 HK1 3333/1
用熟悉的C#,我們這麼寫:
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace LearnJavaFromCharp01
{
class Program
{
static void Main( string [] args)
{
String str = " 1ASDF NI1221312 HK1 2222/1 " + " 1QWW1 NI1232133 HK1 3333 "
+ " 1QWW2 NI1232133 HK1 33331 " + " 1QWW3 NI1232133 HK1 33331/1 "
+ " 1QWW4 NI1232133 HK1 33331 " + " 1QWW5 NI1232133 HK1 3333/1 " ;
String regex = " (1)(?:.|
)*?/\1 " ;
GetRegexString(str, regex);
Console.ReadKey();
}
static void GetRegexString( string oldStr, String strPattern)
{
Regex p = new Regex(strPattern, RegexOptions.Compiled);
MatchCollection mc = p.Matches(oldStr);
for ( int i = 0 ; i < mc.Count; i ++ )
{
Console.WriteLine(mc[i].Value);
}
}
}
}
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace LearnJavaFromCharp01
{
class Program
{
static void Main( string [] args)
{
String str = " 1ASDF NI1221312 HK1 2222/1 " + " 1QWW1 NI1232133 HK1 3333 "
+ " 1QWW2 NI1232133 HK1 33331 " + " 1QWW3 NI1232133 HK1 33331/1 "
+ " 1QWW4 NI1232133 HK1 33331 " + " 1QWW5 NI1232133 HK1 3333/1 " ;
String regex = " (1)(?:.|
)*?/\1 " ;
GetRegexString(str, regex);
Console.ReadKey();
}
static void GetRegexString( string oldStr, String strPattern)
{
Regex p = new Regex(strPattern, RegexOptions.Compiled);
MatchCollection mc = p.Matches(oldStr);
for ( int i = 0 ; i < mc.Count; i ++ )
{
Console.WriteLine(mc[i].Value);
}
}
}
}
模仿著,Java可以這麼寫:
package com.java.learn.csharp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LearnJavaFromCsharp { public static void main(String[] args) {
String str = " 1ASDF NI1221312 HK1 2222/1 " + " 1QWW1 NI1232133 HK1 3333 "
+ " 1QWW2 NI1232133 HK1 33331 " + " 1QWW3 NI1232133 HK1 33331/1 "
+ " 1QWW4 NI1232133 HK1 33331 " + " 1QWW5 NI1232133 HK1 3333/1 " ;
String regex = " (1)(?:.|
)*?/\1 " ;
GetRegexString(str, regex);
}
static void GetRegexString(String oldStr, String strPattern) {
Pattern p= Pattern.compile(strPattern);
Matcher m = p.matcher(oldStr);
while (m.find())
System.out.println(m.group());
}
}
package com.java.learn.csharp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LearnJavaFromCsharp { public static void main(String[] args) {
String str = " 1ASDF NI1221312 HK1 2222/1 " + " 1QWW1 NI1232133 HK1 3333 "
+ " 1QWW2 NI1232133 HK1 33331 " + " 1QWW3 NI1232133 HK1 33331/1 "