Nice programing

정규식으로 괄호 안의 텍스트를 제거하려면 어떻게해야합니까?

nicepro 2020. 11. 29. 12:17
반응형

정규식으로 괄호 안의 텍스트를 제거하려면 어떻게해야합니까?


많은 파일을 처리하려고하는데 파일 이름에서 관련없는 정보를 제거하기 위해 변경해야합니다. 특히 괄호 안의 텍스트를 제거하려고합니다. 예를 들면 :

filename = "Example_file_(extra_descriptor).ext"

괄호식이 중간 또는 끝에 있고 가변 길이 인 파일 전체를 정규식하고 싶습니다.

정규식은 어떻게 생겼습니까? Perl 또는 Python 구문이 선호됩니다.


s/\([^)]*\)//

따라서 Python에서는 다음을 수행합니다.

re.sub(r'\([^)]*\)', '', filename)

괄호 안의 부분 문자열 사이에 다른 문자 가없고() ( (xyz 123)in 과 같이 Text (abc(xyz 123)) 문자 일치하는 패턴은 다음과 같습니다 .

\([^()]*\)

세부 사항 :

코드 조각 제거 :

  • 자바 스크립트 :string.replace(/\([^()]*\)/g, '')
  • PHP :preg_replace('~\([^()]*\)~', '', $string)
  • Perl :$s =~ s/\([^()]*\)//g
  • 파이썬 :re.sub(r'\([^()]*\)', '', s)
  • C # :Regex.Replace(str, @"\([^()]*\)", string.Empty)
  • VB.NET :Regex.Replace(str, "\([^()]*\)", "")
  • 자바 :s.replaceAll("\\([^()]*\\)", "")
  • 루비 :s.gsub(/\([^()]*\)/, '')
  • R :gsub("\\([^()]*\\)", "", x)
  • 루아 :string.gsub(s, "%([^()]*%)", "")
  • Bash / sed :sed 's/([^()]*)//g'
  • Tcl :regsub -all {\([^()]*\)} $s "" result
  • C ++std::regex :std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")
  • 목표 -C :
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error]; NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
  • 스위프트 :s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])

다음을 사용합니다.

\([^)]*\)

당신이 절대적으로 정규식을 사용할 필요가없는 경우 사용하는 펄의 사용을 고려 텍스트 :: 균형 괄호를 제거합니다.

use Text::Balanced qw(extract_bracketed);

my ($extracted, $remainder, $prefix) = extract_bracketed( $filename, '()', '[^(]*' );

{   no warnings 'uninitialized';

    $filename = (defined $prefix or defined $remainder)
                ? $prefix . $remainder
                : $extracted;
}

"정규식이 한 줄로 트릭을 수행 할 때 왜이 모든 작업을 수행합니까?"라고 생각할 수 있습니다.

$filename =~ s/\([^}]*\)//;

Text :: Balanced는 중첩 된 괄호를 처리합니다. 따라서 $filename = 'foo_(bar(baz)buz)).foo'제대로 추출됩니다. 여기에 제공된 정규식 기반 솔루션은이 문자열에서 실패합니다. 하나는 첫 번째 닫는 괄호에서 멈추고 다른 하나는 모두 먹습니다.

$ filename = ~ s / ([^}] *) //; # 반환 'foo_buz)). foo'

$ 파일 이름 = ~ s /(.*)//; # 'foo_.foo'반환

# 텍스트 균형 예제는 'foo _). foo'를 반환합니다.

정규식 동작 중 하나가 허용되는 경우 정규식을 사용하되 제한 사항과 가정을 문서화하십시오.


If a path may contain parentheses then the r'\(.*?\)' regex is not enough:

import os, re

def remove_parenthesized_chunks(path, safeext=True, safedir=True):
    dirpath, basename = os.path.split(path) if safedir else ('', path)
    name, ext = os.path.splitext(basename) if safeext else (basename, '')
    name = re.sub(r'\(.*?\)', '', name)
    return os.path.join(dirpath, name+ext)

By default the function preserves parenthesized chunks in directory and extention parts of the path.

Example:

>>> f = remove_parenthesized_chunks
>>> f("Example_file_(extra_descriptor).ext")
'Example_file_.ext'
>>> path = r"c:\dir_(important)\example(extra).ext(untouchable)"
>>> f(path)
'c:\\dir_(important)\\example.ext(untouchable)'
>>> f(path, safeext=False)
'c:\\dir_(important)\\example.ext'
>>> f(path, safedir=False)
'c:\\dir_\\example.ext(untouchable)'
>>> f(path, False, False)
'c:\\dir_\\example.ext'
>>> f(r"c:\(extra)\example(extra).ext", safedir=False)
'c:\\\\example.ext'

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

For those who want to use Python, here's a simple routine that removes parenthesized substrings, including those with nested parentheses. Okay, it's not a regex, but it'll do the job!

def remove_nested_parens(input_str):
    """Returns a copy of 'input_str' with any parenthesized text removed. Nested parentheses are handled."""
    result = ''
    paren_level = 0
    for ch in input_str:
        if ch == '(':
            paren_level += 1
        elif (ch == ')') and paren_level:
            paren_level -= 1
        elif not paren_level:
            result += ch
    return result

remove_nested_parens('example_(extra(qualifier)_text)_test(more_parens).ext')

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

Java code:

Pattern pattern1 = Pattern.compile("(\\_\\(.*?\\))");
System.out.println(fileName.replace(matcher1.group(1), ""));

참고URL : https://stackoverflow.com/questions/640001/how-can-i-remove-text-within-parentheses-with-a-regex

반응형