Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I have a simple question in regex.

I need to get the first 3 characters of that string ("newtest-test"), the dash and the 2 characters after the dash (like that "new-te").

I use this regex "\w{3}\-\w{2}" but return "est-te". What's wrong?

What I have tried:

I use this regex "\w{3}\-\w{2}" but return "est-te". What's wrong?
Posted
Updated 4-May-21 21:57pm

Quote:
I use this regex "\w{3}\-\w{2}" but return "est-te". What's wrong?

You want to get 2 disjoined parts in a string. You need to match each parts and then join them.
This RegEx: "(\w{3}).*(\-\w{2})" will match each part, you just have to join them.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 
WYCIWYG - What You Code Is What You Get ;)

\w{3}\-\w{2} means:
\w
matches any word character (equivalent to [a-zA-Z0-9_])
{3} matches the previous token exactly 3 times
\- matches the character - literally (case sensitive)
\w
matches any word character (equivalent to [a-zA-Z0-9_])
{2} matches the previous token exactly 2 times 


In your case you need to use Regex.Split Method (System.Text.RegularExpressions) | Microsoft Docs[^] and/or Regex.Replace Method (System.Text.RegularExpressions) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900