2017-03-07 11 views
1

在JavaScript中/(\n.)/g捕獲一個換行符和它後面的第一個字符。 我需要它的反面。這不過是換行符和跟隨它的第一個字符。我想嘗試/(?!\n.)/g但它不起作用。否定這個正則表達式/(n.)/g

const regex = /\n./g; 
const str = `All the world's a stage, 
And all the men and women merely players; 
They have their exits and their entrances,`; 
const subst = ` `; 

// The substituted value will be contained in the result variable 
const result = str.replace(regex, subst); 

console.log('Substitution result: ', result); 

這將返回:

換人結果:整個世界是一個舞臺,第二所有的男人和 演員而已;哎有自己的出口及其出入口,

但是我想:

換人結果:AT

代替一切,除了換行和它後面

的第一個字符
+0

任何例如字符串和預期的結果?你想刪除文本或提取它?也許你只是想使用's.split(/ \ n ./)'? –

+3

使用否定字符類別(set):'/ [^ \ n] ./ g' – falsetru

+0

不幸的是,JavaScript正則表達式不支持lookbehind,但是@ falsetru的註釋應該可以工作 – alex

回答

0

所以你想要做的不是否定,但你可以試試這個;

const data = `All the world's a stage, 
 
And all the men and women merely players; 
 
They have their exits and their entrances,` 
 

 
const func = data => data.replace(/.*((?:\r?\n|\r).).*/g, '$1') 
 

 
console.log(func(data))

+1

請注意,如果字符串包含CR符號,則此解決方案將無法正常工作,因爲'。 '不匹配JS正則表達式中的回車符。另外,由於'.'與LF不匹配,'*?'應該替換爲'*'來更快地工作。 –