Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c# - I want only matching string using regex

I have a string "myname 18-may 1234" and I want only "myname" from whole string using a regex.

I tried using the (^[a-zA-Z]*) regex and that gave me "myname" as a result.

But when the string changes to "1234 myname 18-may" the regex does not return "myname". Please suggest the correct way to select only "myname" whole word.

Is it also possible - given the string in "1234 myname 18-may" format - to get myname only, not may?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE

Judging by your feedback to your other question you might need

(?<!p{L})p{L}+(?!p{L})

ORIGINAL ANSWER

I have come up with a lighter regex that relies on the specific nature of your data (just a couple of words in the string, only one is whole word):

(?<!-)p{L}+

See demo

Or even a more restrictive regex that finds a match only between (white)spaces and string start/end:

(?<=^|s)p{L}+(?=s|$)

The following regex is context-dependent:

p{L}+(?=s+d{1,2}-p{L}{3})

See demo

This will match only the word myname.

The regex means:

  • p{L}+ - Match 1 or more Unicode letters...
  • (?=s+d{1,2}-p{L}{3}) - until it finds 1 or more whitespaces (s+) followed with 1 or 2 digits, followed with a hyphen and 3 Unicode letters (p{L}{3}) which is a whole word (). This construction is a positive look-ahead that only checks if something can be found after the current position in the string, but it does not "consume" text.

Since the date may come before the string, you can add an alternation:

p{L}+(?=[ ]+d{1,2}-p{L}{3})|(?<=d{1,2}-p{L}{3}[ ]+)p{L}+

See another demo

The (?<=d{1,2}-p{L}{3}s+) is a look-behind that checks for the same thing (almost) as the look-ahead, but before the myname.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...