簡體   English   中英

如何在文本文件中找到兩個句子之間的特定單詞

[英]How to find a specific word between two sentences in a text file

假設這是我的文本文件info.txt:

My Name is 
Joe
My Age is 
25
My phone is
Nokia

有沒有一種有效的方法可以使用Javascript返回25(知道它是在“我的年齡”之后出現的?

我正在使用vanilla Javascript和FileReader

你可以簡單地使用RegEx:

let matches = str.match(/My Age Is\s?\n([0-9]+)/i)
let age = matches[1];

這是JSFiddle: https ://jsfiddle.net/tee3y172/

而且,這是如何打破:

  • 我的年齡是 - 匹配這個字符串
  • \\ s? - 可能后跟一個空格(在你的例子中后跟一個空格)
  • \\ n - 后跟一個新行
  • ([0-9]+) - 跟隨任何一系列數字(你也可以使用\\d+ )並將它們分組(這就是perenthesis的用途)。
  • 我 - 忽略案例

然后,分組允許您在索引1處捕獲所需的文本( matches[1] )。

為了匹配“我的年齡”之后的行上的任何內容,您可以使用(.*)除了換行符之外的任何內容:

let matches = str.match(/My Age Is\s?\n(.*)/i)
let age = (!!matches) ? matches[1] : 'No match'; 

這是JSFiddle: https ://jsfiddle.net/spadLeqw/

最簡單的方法是使用regular expression匹配特定單詞后面的數字

 const str = 'My Name is\\nJoe\\nMy Age is \\n25\\nMy phone is\\nNokia'; const match = str.match(/My Age is \\n(\\d+)/)[1]; console.log(match); 

其他資源

txt.split(/Age.+/)[1].match(/.+/)

我會使用.split()作為游標。

 let txt = `My Name is Joe My Age is 25 My phone is Nokia`, age = txt.split(/Age.+/)[1].match(/.+/)[0] console.log(age) 

在包含Age的行中拆分文本內容並匹配下一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM