Translate text into regular expression - MATLAB regexptranslate
文章推薦指數: 80 %
newStr = regexptranslate( op , str ) translates str into a regular expression and returns the result in newStr . Skiptocontent HelpCenterHelpCenter SearchHelpCenter HelpCenter MathWorks SearchMathWorks.com MathWorks Support CloseMobileSearch OpenMobileSearch Off-CanvasNavigationMenuToggle DocumentationHome MATLAB LanguageFundamentalsDataTypesCharactersandStrings regexptranslate Onthispage SyntaxDescriptionExamplesTranslateSpecialCharacterEscapeSpecialCharactersinReplacementTextTranslateWildcardCharactersReplaceTextwithRegularExpressionInputArgumentsopstrVersionHistorySeeAlso DocumentationExamplesFunctionsAppsVideosAnswers TrialSoftware TrialSoftware ProductUpdates ProductUpdates Resources DocumentationExamplesFunctionsAppsVideosAnswers MainContent regexptranslateTranslatetextintoregularexpressioncollapseallinpage SyntaxnewStr=regexptranslate(op,str)DescriptionexamplenewStr=regexptranslate(op,str)translatesstrinto aregularexpressionandreturnstheresultinnewStr. YoucanusenewStrasaregularexpressionintheregexp,regexpi, andregexprepfunctions.Theinputargumentopspecifies thetypeoftranslationthatregexptranslateperforms. Forexample,ifyouspecifyopas'escape', thenregexptranslatetranslatesspecialcharacters instrsothattheyareliteralcharactersinthe output.newStrhasthesamedatatypeasstr.ExamplescollapseallTranslateSpecialCharacterOpenLiveScriptTranslateaspecialcharacterinacharactervectorusingtheregexptranslatefunction.Thenusetheresultasaregularexpressioninregexp.Createacharactervectorthatcontainsthecharacters'\n'.chr='Thesequence\ngeneratesanewline.'chr= 'Thesequence\ngeneratesanewline.' Createaregularexpressionthatfinds'\n'asasequenceofthetwoconsecutivecharacters'\'and'n'.Sincetheregexpfunctioninterprets'\n'asanewlinecharacter,useregexptranslatetocreatearegularexpressiontoescape'\n'.pattern=regexptranslate('escape','\n')pattern= '\\n' Findthestartingindexof'\n'inchr.Topreventregexpfrominterpreting'\n'asanewline,usepatternastheregularexpression.idx=regexp(chr,pattern)idx=14 Callregexpwithoutescaping'\n'.Sinceregexpinterprets'\n'asanewline,itdoesnotfindtheliteralcharactersinchr.Theregexpfunctionreturnsanemptyarraywhenitdoesnotfindamatch.idx=regexp(chr,'\n')idx= [] EscapeSpecialCharactersinReplacementTextOpenLiveScriptCreateastring.str="Putyourmoneyin."str= "Putyourmoneyin." Specifythetext,'$0.02',asthetexttoreplacetheword'money'.Toescapethe'$'and'.'characters,useregexptranslate.r=regexptranslate('escape','$0.02')r= '\$0\.02' Replace'money'usingtheregexprepfunction.newStr=regexprep(str,'money',r)newStr= "Putyour$0.02in." TranslateWildcardCharactersOpenLiveScriptCreateastringarraythatcontainsfilenames.Thenfindonlythefilenamesthatendwith'.mat'.str=["test1.mat","myfile.mat","my-matlab-script.m",... "jan30.mat","table3.xls"]str=1x5string Columns1through4 "test1.mat""myfile.mat""my-matlab-script.m""jan30.mat" Column5 "table3.xls" Tomatchstringswitharegularexpression,specify'*.mat'astheregularexpression.Thentranslatethewildcardcharacter,'*',usingtheregexptranslatefunction.pattern=regexptranslate('wildcard','*.mat')pattern= '.*\.mat' Findmatchingelementsinstrusingtheregularexpressionspecifiedbypattern.matches=regexp(str,pattern)matches=1×5cellarray {[1]}{[1]}{0x0double}{[1]}{0x0double} Createalogicalarray,TF,thatcontains1wherecorrespondingelementsofstrmatchedpattern.ThenindexintostrusingTFtodisplaythefilenamesthatendwith'.mat'.tf=~cellfun('isempty',matches); newStr=str(tf)newStr=1x3string "test1.mat""myfile.mat""jan30.mat" ReplaceTextwithRegularExpressionOpenLiveScriptCreateacharactervectorthatcontainswordsseparatedbywhitespacecharacters,suchasspacesandnewlinecharacters.chr='WhosewoodstheseareIthinkIknow.'; chr=[chrnewline'Hishouseisinthevillagethough']chr= 'WhosewoodstheseareIthinkIknow. Hishouseisinthevillagethough' Specify'\s'asaregularexpressionthatmatcheswhitespacecharacters.Thenreplacethosecharactersinchr.expression='\s'; newChr=regexptranslate('flexible',chr,expression)newChr= 'Whose\swoods\sthese\sare\sI\sthink\sI\sknow.\sHis\shouse\sis\sin\sthe\svillage\sthough' InputArgumentscollapseallop—Translationtype'escape'|'wildcard'|'flexible' Typeoftranslation,specifiedasacharactervectororstring scalar.Youcantranslatespecialcharactersorwildcardcharacters, orreplacetextwithamatchingregularexpression,usingtheoptions inthetable. TypeofTranslationDescription'escape'Translateallspecialcharactersinstr, suchas'$','.','?','[', sothattheyaretreatedasliteralcharacterswhenusedinregexp,regexpi, andregexprep.Thetranslationinsertsabackslash, orescape,character,'\',beforeeachspecial characterinstr.'wildcard'Translateallwildcardand'.'characters instrsothattheyaretreatedasliteralwildcard charactersandperiodswhenusedinregexp,regexpi, andregexprep.Thetranslationreplacesallinstances of'*'with'.*',allinstances of'?'with'.',andallinstances of'.'with'\.'.'flexible'Replacetextinstrwitharegular expressionthatmatchesthetext.Ifyouspecify'flexible', thenalsospecifyaregularexpressiontouseasareplacement:newStr =regexptranslate('flexible',str,expression).Theexpressioninput canbeacharactervectororstringscalar.Thissyntax isequivalenttonewStr=regexprep(str,expression,regexptranslate('escape',expression)). str—Inputtextcharactervector|cellarrayofcharactervectors|stringarray Inputtext,specifiedasacharactervector,acellarrayof charactervectors,orastringarray. VersionHistoryIntroducedbeforeR2006aSeeAlsoregexpi|regexprep|regexp|strfind|strjoin|strsplit|strrep|contains|replaceTopicsRegularExpressions × OpenExample Youhaveamodifiedversionofthisexample.Doyouwanttoopenthisexamplewithyouredits? No,overwritethemodifiedversion Yes × MATLABCommand YouclickedalinkthatcorrespondstothisMATLABcommand: RunthecommandbyenteringitintheMATLABCommandWindow. WebbrowsersdonotsupportMATLABcommands. Close × SelectaWebSite Chooseawebsitetogettranslatedcontentwhereavailableandseelocaleventsandoffers.Basedonyourlocation,werecommendthatyouselect:. Switzerland(English) Switzerland(Deutsch) Switzerland(Français) 中国(简体中文) 中国(English) Youcanalsoselectawebsitefromthefollowinglist: HowtoGetBestSitePerformance SelecttheChinasite(inChineseorEnglish)forbestsiteperformance.OtherMathWorkscountrysitesarenotoptimizedforvisitsfromyourlocation. Americas AméricaLatina(Español) Canada(English) UnitedStates(English) Europe Belgium(English) Denmark(English) Deutschland(Deutsch) España(Español) Finland(English) France(Français) Ireland(English) Italia(Italiano) Luxembourg(English) Netherlands(English) Norway(English) Österreich(Deutsch) Portugal(English) Sweden(English) Switzerland Deutsch English Français UnitedKingdom(English) AsiaPacific Australia(English) India(English) NewZealand(English) 中国 简体中文 English 日本(日本語) 한국(한국어) Contactyourlocaloffice TrialSoftware TrialSoftware ProductUpdates ProductUpdates
延伸文章資訊
- 1regex-translator - npm
Convert a Regular Expression from one flavour to another.. Latest version: 0.2.8, last published:...
- 2Regex Explanation ^.*$ [duplicate] - Stack Overflow
- 3RegExr: Learn, Build, & Test RegEx
Regular expression tester with syntax highlighting, PHP / PCRE & JS Support, contextual help, che...
- 4Regular Expression Analyzer
An online utility that helps analyzing regular expression structure. ... This is a tool to parse ...
- 5regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python...