user941401
user941401

Reputation: 323

finding text until end of line regex

I'm trying to use regex to find a particular starting character and then getting the rest of the text on that particular line.

For example the text can be like ...

V: mid-voice T: tempo

I want to use regex to grab "V:" and the the text behind it.

Is there any good, quick way to do this using regular expressions?

Upvotes: 5

Views: 13272

Answers (3)

Bohemian
Bohemian

Reputation: 425318

Here's the best, cleanest and easiest (ie one-line) way:

 String[] parts = str.split("(?<=^\\w+): ");

Explanation:

The regex uses a positive look behind to break on the ": " after the first word (in this case "V") and capture both halves.

Here's a test:

String str = "V: mid-voice T: tempo";
String[] parts = str.split("(?<=^\\w+): ");
System.out.println("key = " + parts[0] + "\nvalue = " + parts[1]);

Output:

key = V
value = mid-voice T: tempo

Upvotes: 1

AJcodez
AJcodez

Reputation: 34234

For a pattern match try for your example:

V:.*$

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88468

If your starting character were fixed, you would create a pattern like:

Pattern vToEndOfLine = Pattern.compile("(V:[^\\n]*)")

and use find() rather than matches().

If your starting character is dynamic, you can always write a method to return the desired pattern:

Pattern getTailOfLinePatternFor(String start) {
    return Pattern.compile("(" + start + "[^\\n]*");
}

These can be worked on a little bit depending on your needs.

Upvotes: 4

Related Questions