2016-06-07 53 views
0

後如何SomeText如何匹配特定字符串後的模式?

假設我想找到電子郵件地址匹配使用正則表達式的一些模式,那麼我應該只得到:

[email protected]
[email protected]

但我不應該得到的寫在SomeText以上的電子郵件,在JavaScript中使用正則表達式。

我有一個文本文件中的一些事情是這樣的:

在理論計算機科學和形式語言理論,定期 表達式(有時稱爲理性的表達)[1] [2]是一個 序列用於定義搜索模式的字符,主要用於與字符串匹配的模式或字符串匹配,即「查找和 替換」類操作。這個概念出現在20世紀50年代,當時美國[email protected]數學家Stephen Kleene正式描述了一種常規語言,並且被普遍使用於Unix文本處理工具,一個編輯器和一個grep,一個過濾器。

[email protected]

SomeText

NAME1/occupation1/STATE1

[email protected]

正則表達式是計算,各種系統來指定 正則表達式如此有用已經發展爲提供基本和擴展標準的語法和語法 ;現代正則表達式極大地增強了標準。 Regexp處理器在幾個搜索引擎中找到,搜索和 替換幾個文字處理器和文本編輯器的對話框,以及 文本處理實用程序的命令行,如sed和AWK。

名2/occupation2 /狀態2

[email protected]

+0

提示:捕獲組 – anubhava

+0

但如何讓所有的結果SomeText後?請解釋 – PRECISION

+0

使用indexOf和substring(或split)來獲取文本後的文本,然後匹配你所需要的。 –

回答

1

我還沒有找到一種方法來獲得「SomeText」後的兩個電子郵件地址,所以這是我的建議。

剝離關鍵詞前的所有文本。然後,使用更簡單的正則表達式來處理電子郵件地址。下面的正則表達式是 '官方' 一個從emailregex但像 「([\ W \ d] + @ \ w + \ w +)」 會工作得相當好,是一個比較容易理解:)

str = str.substring(str.indexOf("SomeText") + 1); 
results = str.match(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/mg); 
1

您的解決方案:

var string = '\nIn theoretical computer science and formal language theory, a regular expression (sometimes called a rational expression)[1][2] is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. The concept arose in the 1950s, when the American [email protected] mathematician Stephen Kleene formalized the description of a regular language, and came into common use with the Unix text processing utilities ed, an editor, and grep, a filter.\n\[email protected]\n\nSomeText\n\nname1/occupation1/state1\n\[email protected]\n\nRegexps are so useful in computing that the various systems to specify regexps have evolved to provide both a basic and extended standard for the grammar and syntax; modern regexps heavily augment the standard. Regexp processors are found in several search engines, search and replace dialogs of several word processors and text editors, and in the command lines of text processing utilities, such as sed and AWK.\n\nname2/occupation2/state2\n\[email protected]'; 
var someText = 'SomeText'; 
var regExp = new RegExp('\\[email protected]\\S+\\.\\S+','g'); 
var emails = string.split(someText)[1].match(regExp); 
console.log(emails); 
// ["[email protected]", "[email protected]"] 

不要忘記使用RegExp搜索電子郵件。我提供了最簡單的例子。

+0

這比@anubhava解決方案快了2倍。 –

0

你可以做類似下面

var str='your text form which you need to find the email ids'; 

    str=str.replace(/\r\n/g,'##') // need to get all the text in one line otherwise your backrefernce will not work. 

    str=str.replace(/.*sometext(.*)/i,"$1") // remove text before sometext 

    str.match(/[A-Za-z0-9][email protected][A-Za-z]+\.[A-Za-z]+/g)