[英]regex pattern: split() vs find()
我目前正在使用此正則表達式模式= "(?ius)[(?<=\\\\s)]\\\\bgo\\\\b(?=\\\\s)"
。
目的是使用“ go”作為分隔符來過濾t-sql命令。
示例T-SQL代碼:
select * from table1 go
select * from table2
go select * from table3
該模式適用於split()
方法,但不適用於find()
方法。
使用split()
方法的示例結果:
select * from table1
select * from table2
select * from table3
find()
方法的示例結果:
select * from table1 go
select * from table2
go select * from table3
當“ go”在行的結尾或開頭時,它似乎有問題。 如果第一個“開始”后面有一個空格,則它起作用。 我已經嘗試了幾件事,沒有任何運氣。 就我而言,我確實需要使用find()
方法,我不能僅僅依靠split,因為在進行split之前,我需要確認以“行”作為定界符。
我無法重現您的問題:
String pattern="(?ius)[(?<=\\s)]\\bgo\\b(?=\\s)";
String s="select * from table1 go\n" +
"select * from table2\n" +
"go select * from table3";
for(String sub: s.split(pattern))
{
System.out.println("sub: "+sub);
}
System.out.println();
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(s);
int pos;
for(pos=0; m.find(); pos=m.end())
System.out.println("sub: "+s.substring(pos, m.start()));
System.out.println("sub: "+s.substring(pos));
兩種方式都會產生相同的結果。 在這里找到區別將是非常令人驚訝的,因為String.split
方法在內部執行相同的操作。
為了更好地闡明上述問題:
問題似乎不在於split()與matcher()不同,而是正則表達式以及字符串的開頭和結尾。
我的代碼分別對待每一行,所以這真是愚弄我。
正則表達式“(?ius)[(?<= \\ s)] \\ bgo \\ b(?= \\ s)”未捕獲開頭的“ go”和結尾的“ go”。
想法是捕獲“整個單詞”,在這種情況下,單詞是“ go”,因此,如果單詞在字符串的開頭或結尾,我仍然希望包含它。
請參閱上面的示例和評論以進行澄清。
仍然需要解決此問題,沒有太大的成功...
我想我已經找到了解決方案
(?iu)[(?=\\\\s)]\\\\b(Go)|(^go)|(go$)\\\\b(?!\\\\S)
此圖案接縫可否定特殊字符,而不會否定行的開頭和結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.