tags:

views:

66

answers:

5

Hi there,

I have string like this "first#second", and I wonder how to get "second" part without "#" symbol as result of RegEx, not as match capture using brackets

upd: I forgot to add one more special char at the end of string, real string is "first#second*"

+2  A: 
/[a-z]+#([a-z]+)/
hsz
OP apparently does not want to use capture groups (although "not as match capture" may be open to interpretation).
Robusto
+4  A: 

Simple regex:

/#(.*)$/

If you really don't want it to be a match capture, and you know there's a # in the string but none in the part you want, you can do

/[^#]*$/

and the whole regex is what you want.

Charles
+2  A: 

You can use lookaround to exclude parts of an expression.

http://www.regular-expressions.info/lookaround.html

Skyler
+4  A: 

If you must use regex, and you insist on not using capturing groups, you can use lookbehind in flavors that support them like this:

(?<=#).*

Or you can also capture just anything but #, to the end of the string, so something like this:

[^#]*$

The capturing group option, of course, is:

#(.*)
 \__/
   1

This matches the # too, but group 1 captures the part that you want.

Lastly, a non-regex alternative may look something like this:

secondPart = wholeString.substring( wholeString.indexOf("#") + 1 )

There may be issues with some of these solutions if # can also appear (perhaps escaped) anywhere else in the string.

References

polygenelubricants
This is the most complete answer, and the look-behind approach (the first one mentioned here) is the one I would use.
Robusto
+1  A: 

if your using java then

you can consider using Pattern & Matcher class. Pattern gives you a compiled, optimizer version of Regular expression. Matcher gives a complete internals of RE Matches.

Both Pattern.match & String.spilt gives same result where in first is compartively faster.

for e.g)

String s = "first#second#third";
String re = "#";
Pattern p = Pattern.compile(re);
Matcher m = p.matcher();
int ms = 0;
int me = 0;
while( m.find() ) {
    System.out.println("start "+m.start()+" end "+ m.end()+" group "+m.group());
    me = m.start();
    System.out.println(s.substring(ms,me));
    ms = m.end();
}

if other language u can consider using back-reference & groups also. if you find any repetitions.

kadalamittai