ref:
搜尋此網誌
2017年10月18日 星期三
2016年12月25日 星期日
【Java】Difference between matches() and find() in Java Regex
ref:
http://stackoverflow.com/a/4450166
http://stackoverflow.com/a/18409048
http://stackoverflow.com/a/4450166
http://stackoverflow.com/a/18409048
matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123bwhich is not the same as 123 and thus outputs false.
--------------------------------------------------------------------------------------------------------------------------
matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());
System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
Will output:
Found: false Found: true - position 4 Found: true - position 17 Found: true - position 20 Found: false Found: false Matched: false ----------- Found: true - position 0 Found: false Found: false Matched: true Matched: true Matched: true Matched: true
So, be careful when calling
find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.2016年6月19日 星期日
【Java】Copy array
ref:
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/
http://openhome.cc/Gossip/JavaEssence/EqualOperator.html
http://toyangel.pixnet.net/blog/post/27163971
可以使用
int[] newArray = Arrays.copyOf(oldArray,newArray length);
那它和System.arraycopy()有何差別
可以參考以下範例:
以下廢言,因為有這些錯誤,所以才特別筆記了這一篇。
--------------------------------------------------------------------------------
之前犯了低級錯誤,浪費不少時間。
依照記憶寫的,原本想要複製陣列:
很直覺就寫下
old array =xxxx;
new array = old array
當然這省略一些步驟加上這只是pseudo code而以。
所以想當然爾,每次old array改變時,new array也會跟著改變。(因為new array 是指向 old array的reference value → call by value)
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/
http://openhome.cc/Gossip/JavaEssence/EqualOperator.html
http://toyangel.pixnet.net/blog/post/27163971
可以使用
int[] newArray = Arrays.copyOf(oldArray,newArray length);
那它和System.arraycopy()有何差別
可以參考以下範例:
System.arraycopy()
int[] arr = {1,2,3,4,5}; int[] copied = new int[10]; System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy System.out.println(Arrays.toString(copied)); |
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyOf()
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array System.out.println(Arrays.toString(copied)); copied = Arrays.copyOf(arr, 3); System.out.println(Arrays.toString(copied)); |
Output:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]
以下廢言,因為有這些錯誤,所以才特別筆記了這一篇。
--------------------------------------------------------------------------------
之前犯了低級錯誤,浪費不少時間。
依照記憶寫的,原本想要複製陣列:
很直覺就寫下
old array =xxxx;
new array = old array
當然這省略一些步驟加上這只是pseudo code而以。
所以想當然爾,每次old array改變時,new array也會跟著改變。(因為new array 是指向 old array的reference value → call by value)
2015年9月1日 星期二
2015年8月20日 星期四
【Android】實作從html讀取JSON 〈2〉
最近想測試從網頁上讀Json並在Android手機上
舊方法:【Java】實作從html讀取JSON (應該是說在Android API 22之後Apache HTTP Client Removal,Http Get /post的方法被捨棄 )
新方法:以HttpURLConnection實作讀取
因為是要顯示在Android 手機上,那種耗時的網路連線、資料整理的動作並不能在main thread中做處理,所以需要額外開一條Thread在background做處理或是以AsyncTask。
在這裡使用AsyncTask來處理相關動作。(更多關於AsyncTask)
較重要的程式碼,如下:
AndroidManifest.xml
須加上
FetchTask.java
判斷網路是否正常
實作OnFetchListener介面的OnAirDataFetchFinished method
舊方法:【Java】實作從html讀取JSON (應該是說在Android API 22之後Apache HTTP Client Removal,Http Get /post的方法被捨棄 )
新方法:以HttpURLConnection實作讀取
因為是要顯示在Android 手機上,那種耗時的網路連線、資料整理的動作並不能在main thread中做處理,所以需要額外開一條Thread在background做處理或是以AsyncTask。
在這裡使用AsyncTask來處理相關動作。(更多關於AsyncTask)
較重要的程式碼,如下:
AndroidManifest.xml
須加上
<uses-permission android:name="android.permission.INTERNET" />允許使用網路
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
</uses-permission>
允許檢查網路狀態FetchTask.java
public class FetchTask extends AsyncTask<String,Void,String> { interface OnFetchListener { public void OnAirDataFetchFinished(); } private OnFetchListener onFetchListener; public void setOnFetchListener(OnFetchListener listener) { onFetchListener =listener; } @Override protected String doInBackground(String... params) { DataFetcher.getInstance().fetchAirData(); return DataFetcher.getInstance().getResult(); } @Override protected void onPostExecute(String s) { onFetchListener.OnAirDataFetchFinished(); } }DataFetcher.java
public class DataFetcher { private StringBuilder airData = new StringBuilder(); private String path = "http://......"; private ArrayList<AirSiteObject> mItems; private DataFetcher() { } private static DataFetcher mFetcher; public static DataFetcher getInstance() { if (null == mFetcher) { mFetcher = new DataFetcher(); } return mFetcher; } public void fetchAirData() { HttpURLConnection httpURLConnection = null; try { URL url = new URL(path); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.connect(); int status = httpURLConnection.getResponseCode(); switch (status) { case 200: case 201: BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { airData.append(line + "\n"); } bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } } public String getResult() { return airData.toString(); } //JSONParser public ArrayList<AirSiteObject> GetAirData(String result) { mItems =new ArrayList<AirSiteObject>(); JSONObject obj; try { JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { obj = jsonArray.getJSONObject(i); mItems.add(new AirSiteObject(obj)); } } catch (JSONException e) { Log.e("MYAPP", "unexpected JSON exception", e); } return mItems; } }MainActivity.java
private FetchTask mFetchAirDataTask;記得要
implements FetchTask.OnFetchListeneronCraete method
mFetchAirDataTask = new FetchTask();mFetchAirDataTask.setOnFetchListener(this);executeTask();
判斷網路是否正常
private void executeTask() { if (ToolsHelper.isNetworkAvailable(this)) { mFetchAirDataTask.execute(); } else { Toast.makeText(this, "未偵測到網路,請確認網路狀況。", Toast.LENGTH_LONG).show(); } }
實作OnFetchListener介面的OnAirDataFetchFinished method
@Override
public void OnAirDataFetchFinished() {
String result = DataFetcher.getInstance().getResult();
listView.setAdapter(new ViewItemAdapter(this, DataFetcher.getInstance().GetAirData(result)));
if (DataFetcher.getInstance().GetAirData(result).size() == 0) {
Toast.makeText(this, "資料讀取失敗,請稍候再重試。", Toast.LENGTH_LONG).show();
}
}
2015年6月20日 星期六
【Java】path 環境變數
這個動作只需設定一次即可,每次重灌電腦時間間隔時間又隔著那麼長,就稍微紀錄一下,等下次又用到這個基本動作就可以看一下。
ref:http://www.codedata.com.tw/book/java-basic/index.php?p=ch2-3
ref:http://www.codedata.com.tw/book/java-basic/index.php?p=ch2-3
- console mode:
- 執行 echo %Path%指令來看看目前的 Path 變數設定。
- 為了讓作業系統找到 JDK 的工具程式,您要設定 Path 變數包括 JDK 的 bin 資料夾,假設 JDK 的 bin 資料夾是在C:\Program Files\Java\jdk1.7.0_40\bin,則執行以下指令:
- 在 Path=C:\Program Files\Java\jdk1.7.0_40\bin;%Path%的設定中,等號後表示要設定的路徑,首先設定 JDK 的 bin 資料夾路徑,接著用分號區隔,而為了不影響原先 Windows 已有的 Path 變數設定,將%Path%加在後頭,原先的 Path 變數就仍然有效。
- windows mode:
- 開始 → 電腦按滑鼠右鍵 → 內容 → 進階系統設定 → 進階 → 環境變數 , 下方系統變數對話框 → 選Path → 編輯 。編輯系統變數對話框,輸入JDK的bin路徑後接一個分號 → 確定。例如:『C:\Program Files\Java\jdk1.7.0_40\bin;』。
再到console mode下輸入javac,確定成功執行javac工具程式。
2015年1月13日 星期二
【Java】全域常數???
ref:
What is the better way of publishing global constants in Java?
What is the better way of publishing global constants in Java?
Method 1: final class with public static final fieldspublic final class CNST{
private CNST(){}
public static final String C1;
public static final String C2;
static{
C1="STRING1";
C2="STRING2";
}
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.C1);
//System.out.println(CNST.C2);
Method 2: singleton with enumpublic enum CNST{
INST;
public final String C1;
public final String C2;
CNST{
C1="STRING1";
C2="STRING2";
}
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.INST.C1);
//System.out.println(CNST.INST.C2);
Method1的方法較好。
訂閱:
文章 (Atom)