필터 지우기
필터 지우기

Change all indices of a word in a string to '*'.

조회 수: 3 (최근 30일)
Bob Whiley
Bob Whiley 2015년 3월 3일
댓글: Joseph Cheng 2015년 3월 3일
What is the best method to change all indices of a certain word in a string to '*'.
Like if my string were 'Hello, my name is bob, my age is 43.' And I want to change bob and age so it outputs 'Hello, my name is ***, my *** is 43.'

답변 (1개)

Guillaume
Guillaume 2015년 3월 3일
편집: Guillaume 2015년 3월 3일
str = 'Hello, my name is bob, my age is 43.';
regexprep(str, 'bob|age', '***')
  댓글 수: 1
Joseph Cheng
Joseph Cheng 2015년 3월 3일
to expand on Guillaume's answer, since names are probably not going to stay 3 char long.
you can get the position and items using regexp:
filters = {'bob'; 'age'}';
teststr = 'Hello, my name is bob, my age is 43.';
regpattern = sprintf(strjoin(filters, '|'));
matches = regexp(teststr, regpattern, 'match')
pos= regexp(teststr, regpattern)
then knowing what was matched and where the positions are you can replace those index positions with "*".

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

카테고리

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