亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正則表達式獲取 () 之間的字符串

正則表達式獲取 () 之間的字符串

catspeake 2023-03-18 11:22:36
我有文字   var text =  (hello) world this is (hi) text我想寫一個正則表達式函數,這樣我就可以得到parseText(text) // returns ['hello', 'hi']我試過這個但沒有用:'(hello) world this is (hi) text'.match('((.*?))')
查看完整描述

3 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

你可以嘗試: /\([^\)]+\)/g

  1. \(: 轉義字符

  2. [^\)]+: 一個或多個字符包括符號直到)char。

  3. \): 轉義字符

  4. g標志:搜索所有巧合

http://img1.sycdn.imooc.com//64152ea10001f31304980205.jpg

const regex = /\([^\)]+\)/g;

const str = `(hello) world this is (hi) text`;


console.log(

  str.match(regex) // this returns an string array

    .map(i => i.slice(1, -1)) // remove first and last char

);

尖端:

關于第 2 點,您可以更改為[\)]*對零個或多個字符生效。

如果你只需要字符串,你可以使用\w+or \w*

如果你只需要的話,你可以使用/\(\b\w+\b\)/g


查看完整回答
反對 回復 2023-03-18
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

除了使用組或match結果的后處理之外,您還可以使用match前瞻/后視的單個正則表達式:

var text = " (hello) world this is (hi) text"

var output = text.match(/(?<=\().*?(?=\))/g)

console.log(output)

輸出:

[?'hello',?'hi'?]

解釋:

  • (?<=...)...積極回顧。匹配在 be 之前...,但...不包含在匹配中

  • (?<=\()... 正面回顧(角色

  • .*...任何字符的零次或多次

  • .*?...的非貪婪版本.*

  • (?=...)...積極的前瞻,比賽之后是......不包括在比賽中

  • (?=\)))...角色的正面前瞻

  • /.../g...g是全局標志,匹配找到所有,而不僅僅是第一個,出現

  • 不要忘記轉義“特殊字符”,例如括號


查看完整回答
反對 回復 2023-03-18
?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

'(hello) world this is (hi) text'.match(/\([\w]*\)/g)

這將返回[ "(hello)", "(hi)" ],您可以運行另一個解析函數來刪除那個額外的括號。


const text = '(hello) world this is (hi) text';

const list = text.match(/\([\w]*\)/g);

const parsed = list.map(item => item.replace(/\(|\)/g, ''));

console.log(parsed);


查看完整回答
反對 回復 2023-03-18
  • 3 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號