《Java是如何快速煮成C#的?》(一):相似的方法
打算每天花点时间把学习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 "
补充:软件开发 , C# ,