Carl
Carl

Reputation: 11

Finding regex patterns in strings in scala

I’m trying to create a regex that matches strings that have /x+any number/ in them, where anything can be written before or after that.

I tried creating the following regex .*/x+\\d*/.*

An example of a string I’m trying to match is abc/x+10/tomorrow

Strings such as abc/x+/tomorrow should evaluate to false but is true.

Upvotes: 1

Views: 50

Answers (3)

The fourth bird
The fourth bird

Reputation: 163207

You could use for example findFirstIn which will return an Option.

You should match 1+ digits instead and the patten can be shortened to /x\+\d+/

val pattern = """/x\+\d+/""".r
pattern.findFirstIn("abc/x+10/tomorrow").isDefined
pattern.findFirstIn("abc/x+/tomorrow").isDefined

Output

res0: Boolean = true
res1: Boolean = false

Scala demo

Upvotes: 1

vs97
vs97

Reputation: 5859

You were very close, all you needed to do was escape all the / and +, and change \d* (match between 0 and unlimited) to \d+ (match between 1 and unlimited) in order to avoid matching abc/x+/tomorrow:

.*\/x\+\d+\/.*

Regex Demo

Upvotes: 3

Emma
Emma

Reputation: 27723

Maybe,

^.*?x\+\d+.*$

might simply work with proper language-based escapings.

Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Upvotes: 0

Related Questions