1

I am trying to parse a file in the following format.

Case1: 0x5sdf258:648s4df ..;. ABCD hhbdch ; extra text 
Case2: 0xdef58e1:18w4we1 .... HCDC ajdknlmk ;extra text

I want to remove the extra text after the semicolon, So I use the following line

   $row =~ s/;.*//g;

This works in case 2 but fails in case 1. Is there a method in which I can perform my task in both the cases?

2 Answers 2

1

Seems like you want something like this,

$row =~ s/;[^;]*$//g;

OR

$row =~ s/;[^;\n]*$//g;

This would remove the text after the last semicolon (including semicolon).

DEMO

  • [^;]* negated character class which matches any charcater but not of ; , zero or more times.

  • $ asserts that we are at the end.

Code:

use strict;
use warnings;

while(my $line = <DATA>) {
    $line =~ s/;[^;]*$//g;
    print $line."\n";
}


__DATA__
Case1: 0x5sdf258:648s4df ..;. ABCD hhbdch ; extra text 
Case2: 0xdef58e1:18w4we1 .... HCDC ajdknlmk ;extra text

Output:

Case1: 0x5sdf258:648s4df ..;. ABCD hhbdch 
Case2: 0xdef58e1:18w4we1 .... HCDC ajdknlmk
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know the reason but it didn't work for me... Can you provide me an explanation?
I don't know how it works in this demo. In actual code it still fails. I have already chomped the line.
Anyways I figured out another method: $row =~ s/(0x[0-9a-f]+:\s+\w+\s+....\s+.*);.*$/$1/g; Case1 and Case2 text are not a part of line.
0
;(?!.*;).*

Try this.See demo.

https://regex101.com/r/eS7gD7/30

1 Comment

This regex, which should have been explained by its poster, finds a semi-colon, that is not followed by any other semi-colons. But I fear that it uses an inefficient method to arrive at an answer, using a zero-width negative lookahead assertion.

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.