Extract Part of String Before the First Semicolon

Extract part of string before the first semicolon

You could try sub

sub(';.*$','', Type)
#[1] "SNSR_RMIN_PSX150Y_CSH"

It will match the pattern i.e. first occurence of ; to the end of the string and replace with ''

Or use

library(stringi)
stri_extract(Type, regex='[^;]*')
#[1] "SNSR_RMIN_PSX150Y_CSH"

How to split String before first comma?

You may use the following code snippet

String str ="abc,cde,def,fgh";
String kept = str.substring( 0, str.indexOf(","));
String remainder = str.substring(str.indexOf(",")+1, str.length());

Extract text before first comma with regex

Match everything from the beginning of the string until the first comma:

^(.+?),

Javascript: Get first number substring for each semi-colon separated substring

Here is an approach based on a regular expression:

const str = "1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day";

const ids = str.match(/(?<=;)(\d+)|(^\d+(?=,))/gi)

console.log(ids)

bash, extract string before a colon

cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'

Regex - get everything before first comma - python

As @idjaw suggested above, an easier way to accomplish this is to use the split() function:

my_string = 'Unit 5/165,Elizabeth Palace'
ans = my_string.split(',', 1)[0] # maxsplit = 1;
print ans

Result:

Unit 5/165

You could even get away with leave off the maxsplit=1 parameter, in this case:

ans = my_string.split(',')[0]

Also, note that while not technically an error, it is considered best practice to reserve first-letter capitalization of variable names for classes. See What is the naming convention in Python for variable and function names? and PEP8 variable naming conventions.

regex solution:

I noticed that in your example results, when there was a space following the comma (in the string to be analyzed), you got the expected result.

However, when there was no space following the comma, your regex returned "None".

try using the regex pattern (.*?,) rather than .*?,

Here are a couple online tools for debugging and testing regex expressions:

http://pythex.org/

https://regex101.com/

(has an option to generate the code for you, though it may be more verbose than necessary)

PHP substring extraction. Get the string before the first '/' or the whole string

Use explode()

$arr = explode("/", $string, 2);
$first = $arr[0];

In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.



Related Topics



Leave a reply



Submit