Replace group of special character with a single character

조회 수: 2 (최근 30일)
Erivelton Gualter
Erivelton Gualter 2020년 4월 15일
댓글: Erivelton Gualter 2020년 4월 15일
Hello everyone,
I have a question related to regular expression. Let's say I have the following string:
str = vertcat(...
"Whose woods |||||| these are I think I know.", ...
"His house is in the village though;", ...
"He will not see ||| me stopping here", ...
"To '|' watch his woods fill up with snow.")
And I am looking for a new string as in the following:
str = vertcat(...
"Whose woods X these are I think I know.", ...
"His house is in the village though;", ...
"He will not see X me stopping here", ...
"To 'X' watch his woods fill up with snow.")
I have done this task using some hard code to find the '|' clusters and replacing by 'X'
ind = strfind(str,'|')
% ...
However, I have been checking regexp and regexprep, and I believe this is doable using one of this functions in a single line.
  댓글 수: 2
Erivelton Gualter
Erivelton Gualter 2020년 4월 15일
By the way, I also can use regexprep to replace all '|', by 'X', but I would like to replace a group of '|' by X:
expression = '[|]';
replace = 'X';
newStr = regexprep(str,expression,replace)
which returns:
str = vertcat(...
"Whose woods XXXXXX these are I think I know.", ...
"His house is in the village though;", ...
"He will not see XXX me stopping here", ...
"To 'X' watch his woods fill up with snow.")
Walter Roberson
Walter Roberson 2020년 4월 15일
Yup, but my solution changes entire groups.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 4월 15일
regexprep(str, '\|+', 'X')

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by