IT박스

Javascript에서 괄호 사이에 문자열을 가져 오는 정규식

itboxs 2020. 6. 9. 22:17
반응형

Javascript에서 괄호 사이에 문자열을 가져 오는 정규식


괄호 사이에있는 문자열을 반환하는 정규 표현식을 작성하려고합니다. 예를 들어 : 문자열 "("및 ")"사이에있는 문자열을 가져오고 싶습니다.

I expect five hundred dollars ($500).

돌아올 것이다

$500

Javascript에서 두 문자열 사이의 문자열을 얻는 정규식을 찾았습니다.

하지만 정규식을 처음 사용합니다. 정규식에서 '(', ')'를 사용하는 방법을 모르겠습니다


\괄호 일치하는 이스케이프 처리 된 괄호 세트와 캡처 그룹을 작성하는 일반 괄호 그룹을 작성해야합니다.

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");

//matches[1] contains the value between the parentheses
console.log(matches[1]);

고장:

  • \( : 여는 괄호와 일치
  • ( : 그룹 캡처 시작
  • [^)]+: 하나 이상의 비 )문자 와 일치
  • ) : 엔드 캡처 그룹
  • \) : 닫는 괄호 일치

다음은 RegExplained 에 대한 시각적 설명입니다 .


문자열 조작을 시도하십시오.

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
    console.log(newTxt[i].split(')')[0]);
}

또는 정규 표현식 ( 위와 비교하여 다소 느림 )

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
    var str = matches[i];
    console.log(str.substring(1, str.length - 1));
}

임시 전역 변수 사용을 피하기 위해 기능 프로그래밍 스타일에 대한 Mr_Green의 답변포팅 했습니다 .

var matches = string2.split('[')
  .filter(function(v){ return v.indexOf(']') > -1})
  .map( function(value) { 
    return value.split(']')[0]
  })

통화 기호 뒤에 숫자 만 \(.+\s*\d+\s*\)있으면 작동합니다.

또는 \(.+\)괄호 안에 무엇이든지


간단한 솔루션

주의 사항 :이 솔루션은이 질문에서 문자열과 같이 단일 "("및 ")"만있는 문자열에 사용되었습니다.

("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();

온라인 데모 (jsfiddle)


내부 괄호를 제외한 괄호 안의 하위 문자열을 일치시키기 위해 사용할 수 있습니다

\(([^()]*)\)

무늬. 참조 정규식 데모 .

JavaScript에서는 다음과 같이 사용하십시오.

var rx = /\(([^()]*)\)/g;

패턴 세부 사항

  • \( - a ( char
  • ([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
  • \) - a ) char.

To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value:

var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;


for (var i=0;i<strs.length;i++) {
  console.log(strs[i]);

  // Grab Group 1 values:
  var res=[], m;
  while(m=rx.exec(strs[i])) {
    res.push(m[1]);
  }
  console.log("Group 1: ", res);

  // Grab whole values
  console.log("Whole matches: ", strs[i].match(rx));
}


var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));

Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
    alert(matches[i]);
}

This code alerts with all the matches.

References:

search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp

search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

참고URL : https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript

반응형