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
114 views
in Technique[技术] by (71.8m points)

How can I make part of regex optional?

Suppose I have the following regex that matches a string with a semicolon at the end:

".+";

It will match any string except an empty one, like the one below:

"";

I tried using this:

".+?";

But that didn't work.

My question is, how can I make the .+ part of the, optional, so the user doesn't have to put any characters in the string?

question from:https://stackoverflow.com/questions/65842315/update-regex-to-extract-company-register-number

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

1 Answer

0 votes
by (71.8m points)

To make the .+ optional, you could do:

"(?:.+)?";

(?:..) is called a non-capturing group. It only does the matching operation and it won't capture anything. Adding ? after the non-capturing group makes the whole non-capturing group optional.

Alternatively, you could do:

".*?";

.* would match any character zero or more times greedily. Adding ? after the * forces the regex engine to do a shortest possible match.


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

...