2015-09-20 79 views
0

有三種訪問JavaScript Object屬性的方法。使用括號檢測雙引號javascript對象屬性的正則表達式

  1. someObject.propertyName
  2. someObject['propertyName'] // with single quote '
  3. someObject["propertyName"] // with double quote "

括號之間的空間,即,someObject[ 'propertyName' ]someObject[ "propertyName" ],是允許的。

要檢測文本文件中對象someObject的所有屬性,我寫了以下正則表達式。

  1. Regex regex = new Regex(@"someObject\.[a-zA-Z_]+[a-zA-Z0-9_]*");檢測someObject.propertyName表格的屬性。

  2. regex = new Regex(@"someObject\[[ ]*'[a-zA-Z_]+[a-zA-Z0-9_]*'[ ]*\]");檢測someObject['propertyName']表單的屬性。

但是我無法爲表格someObject["propertyName"]的屬性編寫正則表達式。每當我嘗試在正則表達式中寫入"\"時,Visual Studio會給出錯誤。

我在互聯網上發現了一些正則表達式來檢測雙引號文本。例如this。但我不能在正則表達式中添加\[\],visual studio會給出錯誤。

如何檢測someObject["propertyName"]形式的屬性?

我正在使用C#System.Text.RegularExpressions庫。

回答

3

但我不能寫的正則表達式的形式someObject["propertyName"]的屬性:

你可以使用這個表達式:

\bsomeObject\[\s*(['"])(.+?)\1\s*\] 

RegEx Demo

或匹配任何object:

\b\w+\[\s*(['"])(.+?)\1\s*\] 

C#,正則表達式會像

Regex regex = new Regex(@"\bsomeObject\[\s*(['""])(.+?)\1\s*]"); 

正則表達式破碎:

\b  # word boundary 
\w+  # match any word 
\[  # match opening [ 
\s*  # match 0 or more whitespaces 
(['"]) # match ' or " and capture it in group #1 
(.+?) # match 0 or more any characters 
\1  # back reference to group #1 i.e. match closing ' or " 
\s*  # match 0 or more whitespaces 
\]  # match closing ] 
+0

當我嘗試在Visual Studio寫這些正則表達式,它給錯誤。 [dotnetfiddle](https://dotnetfiddle.net/7bo0bS)。 Visual Studio不編譯它。 –

+1

嘗試:'正則表達式正則表達式=新正則表達式(@「\ bsomeObject \ [\ s *(['」「])(。+?)\ 1 \ s *]」);' – anubhava

+0

Thanks:如果你向我解釋,我會很高興。爲什麼視覺工作室給錯誤?我在哪裏可以獲得適當的文檔。我從昨晚開始搜索它並無法解決它。 –

相關問題