Perl에서 여러 단어를 일치시키고 교체 할 때 공백을 어떻게 보존 할 수 있습니까?
-
07-07-2019 - |
문제
원본 텍스트가 있다고 가정 해 봅시다.
here is some text that has a substring that I'm interested in embedded in it.
그 일부와 일치하려면 텍스트가 필요합니다. "has a substring
".
그러나 원본 텍스트와 일치하는 문자열에는 공백 차이가있을 수 있습니다. 예를 들어 일치 텍스트는 다음과 같습니다.
has a substring
또는
has a substring
및/또는 원본 텍스트는 다음과 같습니다.
here is some text that has a substring that I'm interested in embedded in it.
출력하려면 내 프로그램이 필요한 것은 다음과 같습니다.
here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.
또한 원본에서 공백 패턴을 보존하고 시작 및 엔드 마커를 추가해야합니다.
Perl Regexes를 사용하여 이런 일이 발생하는 방법에 대한 아이디어가 있습니까? 나는 시도했지만 결국 혼란스러워졌다.
해결책
PERL 정규 표현식을 사용한 지 얼마되지 않아요.
$match = s/(has\s+a\s+substring)/[$1]/ig
이것은 단어들 사이에 0 이상의 공백 및 Newline 문자를 포착합니다. 원래 분리를 유지하면서 전체 일치를 괄호로 감싸게됩니다. 자동은 아니지만 작동합니다.
당신은 끈을 잡는 것처럼 이것으로 게임을 할 수 있습니다. "has a substring"
그리고 그것을 만들기 위해 그것에 대한 변화를하고 있습니다 "has\s*a\s*substring"
이것을 조금 덜 고통스럽게 만들기 위해.
편집하다: s metacharacter가 Newlines와 Hobbs 수정과 일치한다는 Ysth의 의견을 통합했습니다.
다른 팁
이 패턴은 찾으려는 문자열과 일치합니다.
(has\s+a\s+substring)
따라서 사용자가 검색 문자열을 입력하면 검색 문자열의 공백을 \s+
그리고 당신은 당신의 패턴이 있습니다. 모든 경기를 교체하십시오 [match starts here]$1[match ends here]
어디 $1
일치하는 텍스트입니다.
Regexes에서는 사용할 수 있습니다 +
"하나 이상"을 의미합니다. 그래서 이런 것
/has\s+a\s+substring/
성냥 has
그 다음에 하나 이상의 공백 숯이 그 뒤에 a
그 다음에 하나 이상의 공백 숯이 그 뒤에 substring
.
대체 연산자와 함께 넣으면 다음과 같이 말할 수 있습니다.
my $str = "here is some text that has a substring that I'm interested in embedded in it.";
$str =~ s/(has\s+a\s+substring)/\[match starts here]$1\[match ends here]/gs;
print $str;
그리고 출력은 다음과 같습니다.
here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.
많은 사람들이 제안했습니다 \s+
공백과 일치합니다. 자동으로 수행하는 방법은 다음과 같습니다.
my $original = "here is some text that has a substring that I'm interested in embedded in it.";
my $search = "has a\nsubstring";
my $re = $search;
$re =~ s/\s+/\\s+/g;
$original =~ s/\b$re\b/[match starts here]$&[match ends here]/g;
print $original;
산출:
here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.
문자열의 메타 문자를 피할 수 있습니다. 누군가 관심이 있으시면 추가 할 수 있습니다.
이것은 당신이 그렇게 할 수있는 방법의 예입니다.
#! /opt/perl/bin/perl
use strict;
use warnings;
my $submatch = "has a\nsubstring";
my $str = "
here is some
text that has
a substring that I'm interested in, embedded in it.
";
print substr_match($str, $submatch), "\n";
sub substr_match{
my($string,$match) = @_;
$match =~ s/\s+/\\s+/g;
# This isn't safe the way it is now, you will need to sanitize $match
$string =~ /\b$match\b/;
}
이것은 현재 확인하기 위해 무엇이든합니다 $match
안전하지 않은 문자의 변수.