Split String Only on First Instance of Specified Character

split string only on first instance of specified character

Use capturing parentheses:

'good_luck_buddy'.split(/_(.*)/s)
['good', 'luck_buddy', ''] // ignore the third element

They are defined as

If separator contains capturing parentheses, matched results are returned in the array.

So in this case we want to split at _.* (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

In this example our separator (matching _(.*)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .*) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

We use the s regex flag to make . match on newline (\n) characters as well, otherwise it would only split to the first newline.

split string only on first instance - java

string.split("=", limit=2);

As String.split(java.lang.String regex, int limit) explains:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

The string boo:and:foo, for example, yields the following results with these parameters:

Regex Limit    Result
:     2        { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }

Splitting on first occurrence

From the docs:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

s.split('mango', 1)[1]

Split string based on the first occurrence of the character

You can specify how many substrings to return using string.Split:

var pieces = myString.Split(new[] { ',' }, 2);

Returns:

101
a,b,c,d

Split string with only first instance java

The code below splits on pipes first, and then uses a regex to extract out the properties and attributes. Note that even there, you could probably get away with doing another split.

String response = "I:BARCO@noiclt22815||K:CMS||O:REgetPerspectiveList||A0:googleP||A1:yahooP||A2:gmail||A3:test||A4:hello||A16:CCTV Barco||A17:CCTV: Corridor CC||A18:CCTV: DR Andy Warhol||A19:CCTV: DR Gaudi (Analog)||A20:CCTV: DR Miro||A21:CCTV: Entrance CC||A22:CCTV: Gaudi Demo Room Megapixel||";
String[] metaParts = response.split("\\|\\|");

for (int i=0; i < metaParts.length; ++i) {
String property = metaParts[i].replaceAll("(.*):(.*)", "$1");
String attribute = metaParts[i].replaceAll("(.*):(.*)", "$2");
System.out.println(property + ":" + attribute);
}

As others here have said, regular expressions are not a panacea to cure all your development problems. And splitting is definitely doing the heavy lifting for this problem.

Splitting string from the first occurrence of a character

Use a regex that gets "everything but the first comma". So:

whole_message.match(/([^,]*),(.*)/)

[1] will be the topic, [2] will be the message.

Split on first occurrence of character

Option #1

join back the other splitted elements:

checkHours = "11:30 AM – 4:00 PM, 5:00 PM – 12:00 AM";console.log("checkHours", checkHours);let [start, ...end] = checkHours.split(' – ');end = end.join(" - ");console.log(start);console.log(end);

Split string on the first white space occurrence

If you only care about the space character (and not tabs or other whitespace characters) and only care about everything before the first space and everything after the first space, you can do it without a regular expression like this:

str.substring(0, str.indexOf(' ')); // "72"
str.substring(str.indexOf(' ') + 1); // "tocirah sneab"

Note that if there is no space at all, then the first line will return an empty string and the second line will return the entire string. Be sure that is the behavior that you want in that situation (or that that situation will not arise).

regex strsplit expression in R so it only applies once to the first occurrence of a specific character in each string?

I suggest a matching approach using

^(.*?[RL](?:_pole)?)_(.*)

See the regex demo

Details

  • ^ - start of string
  • (.*?[RL](?:_pole)?) - Group 1:

    • .*? - any zero or more chars other than line break chars as few as possible
    • [RL](?:_pole)? - R or L optionally followed with _pole
  • _ - an underscore
  • (.*) - Group 2: any zero or more chars other than line break chars as many as possible

See the R demo:

library(stringr)
x <- c("SPG_L_subgenual_ACC_R", "SPG_R_MTG_L_pole", "MTG_L_pole_CerebellumGM_L", "SFG_pole_R_IFG_triangularis_L", "SFG_pole_R_IFG_opercularis_L" )

res <- str_match_all(x, "^(.*?[RL](?:_pole)?)_(.*)")
lapply(res, function(x) x[-1])

Output:

[[1]]
[1] "SPG_L" "subgenual_ACC_R"

[[2]]
[1] "SPG_R" "MTG_L_pole"

[[3]]
[1] "MTG_L_pole" "CerebellumGM_L"

[[4]]
[1] "SFG_pole_R" "IFG_triangularis_L"

[[5]]
[1] "SFG_pole_R" "IFG_opercularis_L"


Related Topics



Leave a reply



Submit