簡體   English   中英

拆分字符串並用標點符號和空格分隔

[英]Split a string and separate by punctuation and whitespace

我有一些字符串,例如: I: am a string, with "punctuation". 我想分割字符串,如:

["I", ":", "am", "a", "string", ",", "with", "\"", "punctuation", "\"", "."]

我試過text.split("[\\\\p{Punct}\\\\s]+")但結果是I, am, a, string, with, punctuation ...

我找到了這個解決方案,但Java不允許我用\\w分割。

使用這個正則表達式:

"\\s+|(?=\\p{Punct})|(?<=\\p{Punct})"

你的字符串的結果:

["I", ":", "am", "a", "string", ",", "with", "", "\"", "punctuation", "\"", "."]

不幸的是,有一個額外的元素, ""之后的"" 這些額外的元素只有在空白字符后面有一個標點字符時才會出現(並且總是會出現),所以這可以通過執行myString.replaceAll("\\\\s+(?=\\\\p{Punct})", "").split(regex); 而不是myString.split(regex); (即在拆分之前去除空白)

這是如何工作的:

  • \\\\s+拆分一組空格,因此如果字符是空白字符,我們將刪除這些字符並在該位置拆分。 (注意:我假設一串hello world應該導致["hello", "world"]而不是["hello", "", "world"]
  • (?=\\\\p{Punct})是一個前瞻,如果下一個字符是標點字符,則會分割,但它不會刪除該字符。
  • (?<=\\\\p{Punct})是一個(?<=\\\\p{Punct}) ,如果最后一個字符是標點字符,則會分裂。

編輯:

在回復您的評論時 ,此正則表達式應允許在單詞內標點符號:

"\\s+|(?=\\W\\p{Punct}|\\p{Punct}\\W)|(?<=\\W\\p{Punct}|\\p{Punct}\\W})"

對於這個,你不需要使用replaceAll ,只需要執行myString.split(regex)

這個怎么運作:

這個正則表達式非常相似,但外觀改變了。 \\\\W\\\\p{Punct}匹配一個非單詞字符,后跟一個標點字符。 \\\\p{Punct}\\\\W匹配標點字符后跟非單詞字符。 因此,如果有一個標點符號不在單詞的中間,則每個環視匹配。

或者嘗試這個,收集一個ArrayList:

    String s = "I: am a string, with \"punctuation\".";
    Pattern pat = Pattern.compile( "\\w+|\\S" );

    Matcher mat = pat.matcher( s );
    while( mat.find() ){
        System.out.print( mat.group() +  "/" );
    }
    System.out.println();

輸出:

 I/:/am/a/string/,/with/"/punctuation/"/./

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM