2014-06-14 60 views
0

我有一個以單詞開頭的字符串,我想創建一個從索引0開始到下一個特殊字符索引處結束的子串(space.!,?等)。我怎麼會用正則表達式來做這件事?我可以得到第一個正則表達式匹配的索引嗎?該模式將如何看待?查找特定正則表達式匹配的字符索引

在此先感謝!

回答

1

您可以使用以下內容。

^\w+(?=\W) 

說明

^   # the beginning of the string 
\w+   # word characters (a-z, A-Z, 0-9, _) (1 or more times) 
(?=   # look ahead to see if there is: 
    \W   # non-word characters (all but a-z, A-Z, 0-9, _) 
)   # end of look-ahead 

String s = "foobar!"; 
Pattern p = Pattern.compile("^\\w+(?=\\W)"); 
Matcher m = p.matcher(s); 

if (m.find()) { 
    System.out.println("Start:" + m.start() + " End:" + m.end()); 
    System.out.println(m.group()); 
} 
1

我該如何去做一個正則表達式?

你可以嘗試這樣的事情:

 
^.*?\p{Punct} 
什麼 reluctantly
  • \p{Punct}一個匹配

    我可以得到第一個正則表達式匹配的索引嗎?

    通常,您可以使用Matcher#start獲得正則表達式的匹配指數。

  • 1

    以下打印包含在字符串中的字部分的子字符串(一個\w表示字字符,包括數字,而\W表示非字字符):

    Pattern p = Pattern.compile("(\\w+)[\\W\\s]*"); 
    Matcher matcher = p.matcher("word!,(. [&]"); 
    if(matcher.find()) { 
        System.out.println(matcher.group(1)); 
    } 
    

    輸出:word

    相關問題