0

I am using regression expression to find the patterns such as:

"Today USER ID: 123556 cancelled"
"January USER ID: 236477 renewed"
"February USER ID: 645689 dispute"

Basically I am looking for the string contains "USER ID: " + number. I am using the following code, but it couldn't match anything. Could anyone please give some suggestions?

if (myString.matches("USER ID: ([0-9]+)")) {
      println(a)
}
1
  • string.matches("^.*USER ID: ([0-9]+).*$") will match what you have edited the question to Commented Jun 2, 2015 at 19:55

3 Answers 3

4

It should just be:

if (myString.matches("^USER ID: ([0-9]+)$")) {

without the slashes in the regex string and with a space after USER ID:

just tested and it worked for me as follows:

String string =  "USER ID: 12345";
if(string.matches("^USER ID: ([0-9]+)$")){
     System.out.println("matches");
}

There are lots of good "regex cheatsheets" out there. You can find one such here: http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

Sign up to request clarification or add additional context in comments.

2 Comments

Just noticed that I have char before and after my pattern, e.g. "January USER ID: 12345 cancelled". Then it doesn't seem to work ... is there any additional modification required? Thanks!
string.matches("^.*USER ID: ([0-9]+).*$") will match what you have edited the question to
1
^USER ID: ([0-9]+)$

        ^^

You are missing this space.

3 Comments

Hi, I just added the space, using "/^USER ID: ([0-9]+)$/" still doesn't work
@Edamame use ^USER ID: ([0-9]+)$, not /^USER ID: ([0-9]+)$/
Thanks. Just noticed that I have char before and after my pattern, e.g. "January USER ID: 12345 cancelled". So I modified it to ".USER ID: ([0-9]+)." But the . char doesn't seem to work right, am I missing anything? Thanks!
0

In Scala (following tag in question), define this regex

val re = "USER ID:\\s+\\d+".r

where we allow for several spaces before the sequence of digits; thus for

val a = "Today USER ID: 123556 cancelled"

re.findFirstIn(a)
Option[String] = Some(USER ID: 123556)

delivers Some[String] value if the pattern was found, None otherwise.

To respond whether the pattern was found, consider

re.findFirstIn(a).isDefined
res: Boolean: true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.