2016-11-25 37 views
0

這是一個漩渦課程的問題:元字符「。」在R的漩渦會議

目標是過濾和打印出的位置數據都以元音開始和結束。

下面是代碼:

start_end_vowel<- "^[AEIOU]{1}.+[aeiou]{1}$" #Q1 
    vowel_state_lgl <-grepl(start_end_vowel,state.name) #Q2 
    state.name[vowel_state_lgl] #Q3 

[1] "Alabama" "Alaska" "Arizona" "Idaho" "Indiana" "Iowa"  "Ohio"  "Oklahoma" 

我的問題是,什麼是使用在Q1 .

我知道.適用於任何字符,並且在上述情況下,我們想要用元音開始位置,但爲什麼+[aeiou]{1}$不需要.?事實上,R報告錯誤,如果使用+[aeiou]{1}.$

那麼在這種情況下使用.的適當方式是什麼?

+1

'「。*」'是組件。它說匹配任何系列的字符。然後'「。* [aeiou] $」'表示匹配以元音結尾的任何一系列字符。 [本網站](http://www.regular-expressions.info/)是一個很棒的參考。 – lmo

+0

'.'等同於正則表達式中的通配符,它​​將匹配任何東西。像'* +'這樣的多個操作符都表示匹配「任何數字」和「多於一個」。我保留這張作弊書,以幫助自己:https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ – Nate

回答

0

這裏是你的正則表達式如何讀取故障:

^[AEIOU]{1}.+[aeiou]{1}$ 

^       Start of a line 
[AEIOU]     Match any single character inside the []. A single upper-case vowel 
     {1}    Match the preceding token exactly once 
      .    Match any character (depending on your RegEx engine and options this will behave with slight variation.) 
      +    Match the preceding token as many times as possible. "Any character any number of times" 
      [aeiou]{1} Match a single lower-case vowel. 
         $ Match the end of a line. 

要回答你的問題,[aeiou]{1}$不需要.,因爲它會讀這樣:

[aeiou]{1}.$ 

[aeiou]{1}  Match any lower-case vowel one time 
      .  Match any other character one time 
      $ Match end of line 

這意味着你的正則表達式只會匹配以大寫元音開頭的行。

我在提供RegEx建議之前總是這麼說:我不是RegEx忍者;可能有更好的方法來做到這一點。隨着中說,如果需要,匹配以不區分大小寫的元音開頭的行,而不是使用:

^[aeiouAEIOU].+[aeiouAEIOU]$

注意,我刪除冗餘{1}預選賽。它應該默認匹配一個字符。

+0

謝謝!這是一個非常明確的答案! – leveygao