Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp for :name, :othername, :other

I'm trying to get all the names in a string like this:

:name, :lastName

But I don't seem to find a correct way.

This is what I've tried so far:

/^(:((\w+)(,:(\w+))+).*)$/

In Java:

Pattern a = Pattern.compile("(:((\\w+)(,:(\\w+))+).*)");
Matcher m = a.matcher(":name,:lastName,:bd");
if( m.matches() ) { 
  for( int i = 0 ; i < m.groupCount() ; i++ ) { 
    out.println( i + " = " + m.group( i ) );
  }   
}

Output:

0 = :name,:lastName,:bd
1 = :name,:lastName,:bd
2 = name,:lastName,:bd
3 = name
4 = ,:bd

And I'm trying to get a variable number of groups containing [name, lastName, bd]

EDIT

BTW, I'm trying to get this for a more complex regex to match simple things like:

 insert into table values ( :a, :b, :c )

/insert\s+into\s+(\w+)\s+values\s+(\( HERE IS MY QUESTION \))/
like image 546
OscarRyz Avatar asked Dec 09 '25 10:12

OscarRyz


2 Answers

Is it a requirement that you place the result in different groups? This will oterwise work:

Pattern a = Pattern.compile(":([^,]+)");
Matcher m = a.matcher(":name,:lastName,:bd");
while (m.find()) {
    System.out.println(m.group(1));
}

Edit: ... and you can use split if you want to get an array of results:

String data = ":name,:lastName,:bd";
String[] parts = data.replace(":", "").split(",", -1);
System.out.println(Arrays.toString(parts));
like image 165
Kaj Avatar answered Dec 11 '25 23:12

Kaj


Perhaps you want this:

public static void main(String[] args) {
    Pattern a = Pattern.compile(":(\\w+)");
    Matcher m = a.matcher("insert into table values ( :a, :b, :c )");
    while (m.find()) {
        System.out.println(m.group(1));
    }
}

which outputs:

a
b
c
like image 36
MarcoS Avatar answered Dec 12 '25 00:12

MarcoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!