2015-01-05 85 views
0

如何寫一個regex來匹配這個(見箭頭):正則表達式在雙引號內(單獨)與單引號匹配?

"this is a ->'<-test'" // note they are quotes surrounding a word 

等相匹配呢?

"this is a 'test->'<-" 

在JavaScript中? (然後,用雙引號替換它們)

我想用兩個正則表達式分別匹配它們。

+0

你想匹配他們seperatly或匹配字符串中的每個'''? – nu11p01n73R

+0

@alexchenco分別與2個正則表達式。 – alexchenco

+2

'「這是'測試'還有另外一個'測試'''那麼這裏發生了什麼? – nu11p01n73R

回答

2

對於第一種情況:

var str = '"this is a \'test\'"'; 
var res = str.replace(/'/, "#"); 
console.log(res); 

=> "this is a #test'" 

對於第二種情況:

var str = '"this is a \'test\'"'; 
var res = str.replace(/(.*(?='))'/, "$1#"); 
console.log(res); 

=> "this is a 'test#" 

也明白第二種情況是隻考慮最後' 和第一種情況下才會考慮第一個'

更新:

如果你想更換第一 '的東西所有的發生試試這個

var str = '"this is a \'test\' there is another \'test\'"'; 
var res = str.replace(/'(\w)/g, "#$1"); 
console.log(res); 

=> "this is a #test' there is another #test'" 

第二occurence試試這個:

var str = '"this is a \'test\' there is another \'test\'"'; 
var res = str.replace(/(\w)'/g, "$1#"); 
console.log(res); 

=> "this is a 'test# there is another 'test#" 

這ofcourse是一個非常操縱性的方法,你可能會面臨異常情況。正則表達式和本身這樣的恕我直言用法是一個過於複雜的方法

+0

這是有希望的,但不會在字符串中找到所有''''。正如OP在評論中所提到的「這是一個'測試'',還有另一個'測試'''作爲輸入。在這裏它只發現第一次發生 – nu11p01n73R

+1

@ nu11p01n73R在這種情況下檢查我的更新先生 – aelor

+0

現在好了。如果你不介意請不要打電話給我先生不是那麼古老:P – nu11p01n73R

3

第一種情況

/'\b/ 

Regex Demo

"this is a 'test' there is another 'test'".replace(/'\b/g, '"')) 
=> this is a "test' there is another "test' 

第二種情況

/\b'/ 

Regex Demo

"this is a 'test' there is another 'test'".replace(/\b'/g, '"')) 
=> this is a 'test" there is another 'test" 
+0

我喜歡http://www.regexr.com/更好 –

+1

@AliNaciErdem它是一個很棒的工具,但它只支持JavaScript,因爲regex101支持php和python – nu11p01n73R

1

Depence弦上,對於給定的字符串"this is a ->'<-test'"

"this is a ->'<-test'".replace(/'/g,"\""); // does both at the same time 
// output "this is a ->"<-test"" 
"this is a ->'<-test'".replace(/'/,"\"").replace(/'/,"\"") // or in two steps 
// output "this is a ->"<-test"" 
// tested with Chrome 38+ on Win7 

在第一個版本的g,並全局替換,因此替換所有'\"(反斜槓僅是逃逸字符)。第二個版本只取代第一個發生。

我希望這有助於

如果你真的想匹配一旦第一,一旦最後一個(不選擇/更換第一),你會做這樣的事情:

"this is a ->'<-test'".replace(/'/,"\""); // the first stays the same 
// output "this is a ->"<-test'" 
"this is a ->'<-test'".replace(/(?!'.+)'/,"\""); // the last 
// output "this is a ->'<-test"" 
// tested with Chrome 38+ on Win7 
相關問題