Regular Expressions (REGEX): Basic symbols - Scripting Blog
文章推薦指數: 80 %
Regular Expressions (REGEX): Basic symbols · Take special properties away from special characters: \. would be used to represent a literal dot ... Skiptomaincontent RegularExpressions(REGEX):BasicsymbolsKoryThacher July31st,20180 WelcomebacktotheRegExguide.LastpostwetalkedalittlebitaboutthebasicsofRegExanditsuses.Imentionedthemostimportantthingistounderstandthesymbols.Todaywe’lleaseinwithsomeofthebasicstogetusgoing,butlaterwewillexpandontheseandseesomeotheroptionswehave. . isusedtorepresentanysinglecharacter,asidefromanewline,soitwillfeelverysimilartothewindowswildcard? \ istheescapecharacterforRegEx,theescapecharacterhastwojobs: Takespecialpropertiesawayfromspecialcharacters:\. wouldbeusedtorepresentaliteraldotcharacter.\\ isusedforaliteralbackslashcharacter. Addspecialpropertiestoanormalcharacter:\d isusedtolookforanydigit(we’llseemoreoftheseinabit) Wecanuse{} tospecifyquantityinafewdifferentwaysbyattachingthemtocharactersorsymbols. {exactnumber} sosomethinglike\d{2} says“lookforexactlytwodigits” {min,max} sosomethinglike\d{2,4} says“lookforatleasttwodigits,butkeepgrabbingthemuntilyouhavemorethan4” {min,} willcheckforaminimumwithnomaxcap,so\d{2,}says“lookforatleast2digits,butkeepgrabbingthemuntilyouseesomethingthatisn’tadigit” + isashortcutfor{1,0} soyoucansay“oneormore” * isashortcutfor{0,} soyoucansay“zeroormore”(becarefulwiththatone!) ? is{0,1} soyoucansay“thismayormaynotbehere”.Couldbeusefulforlinksthatmayormaynothavean“s”for“http”/”https” Characterclasseslike\d aretherealmeat&potatoesforbuildingoutRegEx,andgettingsomeusefulpatterns.Thesearecasesensitive(lowercase),andwewilltalkabouttheuppercaseversioninanotherpost.Threeofthesearethemostcommontogetstarted: \d looksfordigits \s looksforwhitespace \w looksforwordcharacters Wewilltalkabout\p inafutureposttomatchmorespecificsymbolgroups. Letsputittogetherandtryacouplethings.We’llstilluse-match and$matches[0] fornow,butwe’llusesomeotherthingstoleverageRegExoncewearecomfortablewiththebasicsymbols. We’llusethesameshellaswehadinthelastpost andthesameMOCK_DATA asbefore.Thistime,letsmatchemails.Tryityourselffirst! Hint: TheemailsseemtoallbeFirstletterfollowedbylastname,sojustsomewordcharacter.Thenan@symbol,morewordcharacter,thenadot,thenmorewordcharacters! Answer: "\w+@\w+\.\w+" Puttingittogether: #grabourdata $file=get-content"$PSScriptRoot\MOCK_DATA.txt" #makeourpattern $regex="\w+@\w+\.\w+" #loopthrougheachline foreach($linein$file) { #ifourlinecontainsourpattern,writethematcheddatatothescreen if($line-match$regex) { $matches[0] } } Results: [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] Onceagain,youcanfinditongithere. Hopeyou’reenjoyingRegExsofar,andstartingtoseehowitcanbeprettyuseful!Nexttimewewilltakealookatgroupingtoextractdifferentpiecesofdata,andusing[regex]insteadofjust$matches. Asalways,don’tforgettorate,commentandshare!Letmeknowwhatyouthinkofthecontentandwhattopicsyou’dliketoseemeblogaboutinthefuture. KoryThacher PremierFieldEngineer Follow Readnext PowerShellPowerTip:HistoryofcommandswithPSReadline OneofthereallycoolthingsPSReadlineprovides(moduleshippingonv5+)isn'tasimmediatelyobviousasthesyntaxhighlighting.Itoffersapersistenthistorythatis... KoryThacherAugust7,2018 0comment RegularExpressions(REGEX):Grouping&[RegEx] WelcomebacktotheRegExcrashcourse.Lasttimewetalkedaboutthebasicsymbolsweplantouseasourfoundation.Thisweek,wewillbelearninganewwaytoleverage... KoryThacherAugust14,2018 1comment 0comments Commentsareclosed. Logintoedit/deleteyourexistingcomments PowerShellResources PowerShellDocumentation ScriptingForums PowerShellForums PowerShellonTechCommunity PowerShell.org-CommunityResource Topics .csv.NET.NETCore.NETFramework2009SummerScriptingGames2010ScriptingGames2011ScriptingGames2012ScriptingGames2013ScriptingGames2014ScriptingGames2014WinterScriptingGames2015HolidaySeries4.070-410AaronNelsonAccess.ApplicationACLsactivationActiveDirectoryActiveDirectoryApplicationMode(ADAM)ActiveXDataObjects(ADO)AdamBertramAdamDriscollAdamHaynesAdminFirstStepsADO.NETADODB.RecordsetADOR.RecordsetADSIAdvancedAdvancedEvent1AdvancedEvent10AdvancedEvent2AdvancedEvent3AdvancedEvent4AdvancedEvent5AdvancedEvent6AdvancedEvent7AdvancedEvent8AdvancedEvent9AdvancedFunctionsAlanByrneAlanMorrisAlexVerboonandjobsAndersWahlqvistAndroidAndySchneideranonymousAntivirusApp-VapplicationsArnaudPetitjeanArrayArraysarrayshashtablesarrayshashtablesanddictionaryobjectsarrayshashtablesanddictionaryobjectsASCIIAshleyMcGloneAsiaGandeckaASP.NETCoreassociatorsofAttributesAudioAuthorsAutomaticVariablesAutomationAzureAzureAutomationAzureADbackgroundjobsbackupbackupandsystemrestorebadgeBartekBielawskiBashbasiccomputerinformationbasichardwareandfirmwareBasicHardwareinformationbasicinformationBasicsBATCHmanbatteriesandpowersuppliesBeginnerBeginnerEvent1BeginnerEvent10BeginnerEvent2BeginnerEvent3BeginnerEvent4BeginnerEvent5BeginnerEvent6BeginnerEvent7BeginnerEvent8BeginnerEvent9BenPearceBenVierckBestPracticebestpracticesBhargavShuklaBillGrauerBillStewartBitLockerBITSBobStevensBoeProxBrandonShellbreakpointBrentFormanBrianHitneyBrianJackettBrianLalancetteBrianWilhiteBrianWrenBrucePayetteBuckWoodyBuildyourowncmdletC#CertificatecertificatesChadMillerchangejournalChendrayanVenkatesanChrisBelleeChrisCampbellChrisConteChrisDentChrisO'PreyChrisWeaverChrisWuChrissyLeMaireChristopherWeaverCIMClassesClaudiaFergusonclientapplicationsclient-sidemanagementclient-sideprintingClintHuffmanClintonKnightcloudCloudServicesColorCOMCOMandDCOMCommaandotherdeliminitedfilesCommaandotherdelimitedfilesCommaseparatedandotherdelimitedfilescommentscommunityCompare-ObjectcompressedfilescomputeraccountsComputersConfigurationManagerConnectconsoleContinuousDeliveryContinuousIntegrationCoreyRothCPUCredentialGuardCryptographyCSVandotherdelimitedfilesDACLSandSACLSDanReistDanSheehanDanielCruzDatadatabasesDataGriddatesdatesandtimesDaveBishopDaveWyattDavidMoravecDavidO’BriendebugdebuggerdebuggingDebuggingandDiagnosticsDefenderDennisWhitneyDeploymentandUpgradeDesktopdesktopmanagementDesktopMgmtDesktopTasksDHCPDHCPserverDiaReevesdialogboxesdirectoriesDirectorydiskdrivesandvolumesdiskquotasDisksDISMdisplayingoutputDNSDNSserverDockerDoctorScriptoDomainControllersdomainsDonGillDonJonesDonWalkerDougFinkedownloadingfilesDSCduedatesedwilsonEdgeeditorendpointenumEnumsEnvironmentenvironmentalvariableEricWrighterrorhandlingEvent1Event10Event2Event3Event4Event5Event6Event7Event8Event9eventlogseventlogsandmonitoringEventingandMonitoringEventsEventsandLoggingeventsandmonitoringExcelspreadsheetExcel.ApplicationExchangeExchange2010ExchangeOnlineexpertcommentatorsExtensionsF#FacebookfaqFASTESP5.3SP3FilefilesfilesandfoldersfilesystemFileSystemObjectfirewallfoldersFormattingoutputfunctionsFundamentalsGaryJacksonGarySiepserGeneralManagementgeneralmanagementtasksGeneralMgmtTasksGeorgesMaheuGershonLevitzGet-RandomgettingstartedGlennSizemoreGlynCloughgraphicalgraphicsGregLindsayGroupPolicyGroupinggroupsguestbloggerGuestBloggerGUIhardwarehashhashtablesHashTableshashtablesanddictionaryobjectsHeathLawsonHelpHeyScriptingGuyHistoricalDebuggingHistoryholiday2013HonoraryScriptingGuysHyper-VHyperVIwasthereIanFarrigniteIgnite2015Ignite2016IISIngoKarsteininputInstallIntellisenseinternetInternetExplorerInternetExplorer7InternetSearchInvoke-RestMethodInvoke-WebRequestiOSIoTISEISEeditingJakobGottliebSvendsenJamesBrundageJamesKehrJamesO’NeillJanEgilRingJasonHelmickJasonHofferleJasonMorganJasonRybergJasonWalkerJavaJDPlatekJeffWoutersJefferyHicksJeremyEngelJimChristopherjobsJoelBennettJoelStidleyJoelVickeryJohnFerringerJohnSlackJonNewmanJonathanAllenJonathanMeddJonathanTylerJonathanYongJoshAtwellJoshGavantJsonjudgesjudgingcriteriaJudithHermanJuneBlenderJustinHallkScriptingTechniquesKarlMitschkeKeithHIllKeithMayerKenMcFerronKendalVanDykeKevinKlineKirkMunroKlausSchulteKoryThacherkorytLaerteJuniorleaderboardLeeHolmesLidoPagliaLINUXlocalaccountmanagementlocalaccountslocalaccountsandWindowsNT4.0accountslocaluseraccountmanagementLogAnalyticslogparserLoggingandeventslogonsessionslogsLogsandloggingLogsandmonitoringloopingLYNCManagementMarcCarterMarcvanOrsouwMarcoShawMarkMorowczynskiMarkSchillMarkTabladillomaskingpasswordsmathMattBongioviMattGraeberMattHesterMattHitchcockMattTisdaleMatthewHitchcockMatthewKerfootMCSEMDTMediaMessaging&CommunicationmessagingandcommunicationMetadataMichaelBlumenthalMichaelFrommholdMichaelWellsMicrosoft365MicrosoftAccessMicrosoftExcelMicrosoftExchange2003MicrosoftExchange2007MicrosoftExchange2010MicrosoftOfficeMicrosoftOutlookMicrosoftPowerPointMicrosoftVisioMicrosoftWordmigrationMikeFRobbinsMikeFalMikeO'NeillMikePfeifferMikeStiersMiniScriptingGamesMobilemoduleModuleBrowsermodulesmonitoringMonitoringandlogsMSOMSmultimediaNanoServerNetworkAdapternetworkadaptersnetworkingNicholasCainNicolasBlankNiklasGoudeNormanDrewsNumbersObjectsODBCOfficeOffice365Office365APIOffice365SitesofficialrulesOliverLipkauoperatingsystemOracleotherDirectoryServicesOUsOut-GridViewOutputpackettracespagefilesparameterPartnerspasswordsPatrickMercierPaulGreeleyPaulHiginbothamPauloMorgadoPerPedersenperformanceperipheralsanddevicespermissionandsecuritypermissionsPesterPhilBraniffpinvokepipelineplain-textlogsPodcastportsportsandslotspowermanagementPowerCLIPowerShellPowerShell3powershell3.0PowerShell4PowerShell4.0Powershell5PowerShell5.0PowerShellbestpracticesPowerShellGalleryPowerShellGetPowerTipPowerTip:FindDefaultSessionConfigConnectioninPowerShellSummary:FindthedefaultsessionconfigurationconnectioninWindowsPowerShell.HowcanIdeterminewhatdefaultsessionconfigurationPrintprintserversPrintServersPrintQueuesandprintjobsprinterportsdriversanddevicesPrintersprintingprizewinnersProcessprocessesProcmonprofileprofilespromptProvidersPSDrivesPSGalleryPSGetPSProvidersPSReadLinequerycompletionserverqueuesQuick-HitsFridayRagnarHarperRaimundAndreeRajeshB.RavindranathRavikanthRaymondMitchellreceivinginputRecycleBinReferenceRegExregistryregularexpressionsreliabilityremoteRemoteEndpointremotingReportingReportsResourceGuideresourceownershipretrievinginputRhysCampbellRichPrescottRichardDiphoornRichardSiddawayRobCampbellRobertRobeloRodColledgeRODCRohnEdwardsRolfMasuchRPCRSATRSSRSSfeedsRudolfVeselyrunningrunningscriptsRunspaceSANScheduleTasksscheduledtaskscheduledtasksSchemaSCOM2007R2ScopeScottGeScriptAnalyzerScriptBrowserScriptCenterscriptsigningScripterScripti9ngTechniquesScriptingScriptingGamesScriptingGames2014ScriptingGuy!ScriptingTechniquescriptingtechniquesscriptingtemplatesScriptingWifeSeanKearneySeanMcCownsearchSearchingsearchingActiveDirectorysecuritySelect-StringsendingemailsendingmailSeriesSerkanVarogluServerApplicationsServer-SideManagementServer-SideupdateserversserversWSUSServicePacksandHotFixesservicepacksandhotfixesservicessessionsSethBrandesShadowCopyShaneHoeyShaneNelsonShannonMasharedfoldersandmappeddrivesSharePointSharePoint2010SharePointOnlineShayLevyshell.applicationSherifTalaatShubertSomerSiegfriedJagottsitesandsubnetsSkyDriveSMTPMailSnapshotDebuggerSnippetsSoftwareSolutionssortingspecialfolderssplattingsponsorsponsorsSQLSQL2012SQLServerSQLServer2008SQLServer2012startupandshutdownStefanRothStefanStrangerStephanevanGulickSteveJefferySteveMurawskiStevenMurawskistorageStreamsstringstringmanipulationStringsstudyguideSusanFerrellSusanHillSysinternalsSystemCenterSystemRestoreTaylorGibbTCP/IPTeamsTechEdTechEd2014TechEd_2010TechEd2012TeresaWilsonTerminalServerTerriDonahueTestExperienceTestingTexttextfilesTextmanipulationTFSTheMAKThiyaguThomasLeeThomasRaynerThomasStringerTiborSoosTimBoltontimesyncTimeSynchronizationTimeSpanTimothyWarnerTipsandTricksTobiasWeltnerToddKlindtTomMoserTomShinderTomeTanasovskitop20tracetracestranslationTrevorSullivantroubleshootingTypesupdatesUpgradeUSBuseraccountsusergroupsusersusingtheInternetusingthewebVariableVariablesVBVBScriptVBScriptmigrationVersionversioninformationvideovideoanddisplayvideoRAMVideosVinayPamnaniVirtualMachinesvirtualserverVisualStudioVisualStudio2017VisualStudioAppCenterVisualStudioCodeVisualStudioforMacVisualStudioIDEVisualStudioLiveShareVisualStudioMarketplaceVisualStudioPreviewsVisualStudioSubscriptionsVisualStudioToolsforAIVisualStudioToolsforXamarinVMMWalidMoselhyWebpagesandHTAsWebServicewebservicesWebinarWebsitesWeekendScripterWeiHaoLimWillAndersonWillMartinWillSteeleWilliamStanekWin32Windows10Windows7Windows8Windows8.1WindowsAzureWindowsExplorerWindowsManagementFrameworkWindowsMediaPlayerandaudioWindowsNTWindowsPEWindowsPowerShellWindowsPowerShell3.0WindowsPowerShell4.0WindowsPowerShell5WindowsPowerShell5.0WindowsPowerShellISEWindowsPowerShllWindowsServerWindowsServer2003WindowsServer2008R2WindowsServer2012WindowsServer2012R2WindowsServer2016WindowsToGoWindowsUpdateWindowsVistaWindowsWindowsPowerShellWinNTWinRMWMIWordWord.ApplicationWorkflowWorkflowsWPFWPKwrapupwritingwritingscriptsWshShellWSUSXamarinXMLxpathYanPanYuriDiogenesZacharyLoeberZuneandothermediadevices Archive October2021 February2021 September2020 December2019 November2019 October2019 September2019 August2019 July2019 November2018 September2018 August2018 July2018 June2018 May2018 April2018 March2018 February2018 January2018 December2017 November2017 October2017 August2017 July2017 February2017 January2017 December2016 November2016 October2016 September2016 August2016 July2016 June2016 May2016 April2016 March2016 February2016 January2016 December2015 November2015 October2015 September2015 August2015 July2015 June2015 May2015 April2015 March2015 February2015 January2015 December2014 November2014 October2014 September2014 August2014 July2014 June2014 May2014 April2014 March2014 February2014 January2014 December2013 November2013 October2013 September2013 August2013 July2013 June2013 May2013 April2013 March2013 February2013 January2013 December2012 November2012 October2012 September2012 August2012 July2012 June2012 May2012 April2012 March2012 February2012 January2012 December2011 November2011 October2011 September2011 August2011 July2011 June2011 May2011 April2011 March2011 February2011 January2011 December2010 November2010 October2010 September2010 August2010 July2010 June2010 May2010 April2010 March2010 February2010 January2010 December2009 November2009 October2009 September2009 August2009 July2009 June2009 May2009 April2009 March2009 February2009 January2009 December2008 November2008 October2008 September2008 August2008 July2008 June2008 May2008 April2008 March2008 February2008 January2008 December2007 November2007 October2007 September2007 August2007 July2007 June2007 May2007 April2007 March2007 February2007 January2007 December2006 November2006 October2006 September2006 August2006 July2006 June2006 May2006 April2006 March2006 February2006 January2006 December2005 November2005 October2005 September2005 August2005 July2005 June2005 May2005 April2005 March2005 February2005 January2005 December2004 November2004 October2004 September2004 August2004 Login CodeBlock × Pasteyourcodesnippet Cancel Ok
延伸文章資訊
- 1116 - Stack Overflow
The regular expression for this is really simple. Just use a character class. The hyphen is a spe...
- 2Metacharacters - IBM
- 3Regex symbol list and regex examples - Codexpedia
Regex symbol list and regex examples ; \b Backslash and b, matches a word boundary. For example, ...
- 4Regular expressions 1. Special characters
The following characters are the meta characters that give special meaning to the regular express...
- 5Simple RegEx Tutorial
Regular Expression can be used in Content Filter conditions. ... These symbols indicate the start...