Xóa các bản sao khỏi chuỗi


17

Lấy cảm hứng từ câu hỏi StackOverflow khó hiểu này .

Ý tưởng rất đơn giản; đã cho một Chuỗi và một chuỗi Chuỗi, loại bỏ bất kỳ trường hợp từ nào trong mảng (trường hợp bỏ qua) khỏi Chuỗi đầu vào khác với Chuỗi đầu tiên, cùng với bất kỳ khoảng trắng bổ sung nào có thể để lại. Các từ phải khớp với toàn bộ các từ trong Chuỗi đầu vào và không phải là các phần của từ.

ví dụ như "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", ["cat", "mat"]đầu ra"A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat"

Đầu vào

  • Đầu vào có thể được lấy dưới dạng Chuỗi và một chuỗi Chuỗi hoặc mảng Chuỗi trong đó Chuỗi đầu vào là thành phần đầu tiên. Các tham số này có thể theo thứ tự.
  • Chuỗi đầu vào có thể không được lấy làm danh sách các Chuỗi được phân tách bằng dấu cách.
  • Chuỗi đầu vào sẽ không có khoảng trắng ở đầu, cuối hoặc liên tiếp.
  • Tất cả đầu vào sẽ chỉ chứa các ký tự [A-Za-z0-9] ngoại trừ Chuỗi đầu vào cũng bao gồm cả khoảng trắng.
  • Mảng đầu vào có thể trống hoặc chứa các từ không có trong Chuỗi đầu vào.

Đầu ra

  • Đầu ra có thể là giá trị trả về từ một hàm hoặc được in ra STDOUT
  • Đầu ra phải trong cùng trường hợp với Chuỗi ban đầu

Các trường hợp thử nghiệm

the blue frog lived in a blue house, [blue] -> the blue frog lived in a house
he liked to read but was filled with dread wherever he would tread while he read, [read] -> he liked to read but was filled with dread wherever he would tread while he
this sentence has no matches, [ten, cheese] -> this sentence has no matches
this one will also stay intact, [] -> this one will also stay intact
All the faith he had had had had no effect on the outcome of his life, [had] -> All the faith he had no effect on the outcome of his life
5 times 5 is 25, [5, 6] -> 5 times is 25
Case for different case, [case] -> Case for different
the letters in the array are in a different case, [In] -> the letters in the array are a different case
This is a test Will this be correct Both will be removed, [this,will] -> This is a test Will be correct Both be removed

Vì đây là mã golf, số byte thấp nhất sẽ thắng!

Câu trả lời:


9

R , 84 byte

function(s,w,S=el(strsplit(s," ")),t=tolower)cat(S[!duplicated(x<-t(S))|!x%in%t(w)])

Hãy thử trực tuyến!

Ít hơn 100 byte cho một thách thức không phải là ?

Giải trình:

Sau khi chia chuỗi thành các từ, chúng ta cần loại trừ các chuỗi

  1. trùng lặp và
  2. trong w

hoặc cách khác, bật cái đầu đó lên, giữ những cái đang

  1. sự xuất hiện đầu tiên của một từ HOẶC
  2. không trong w.

duplicatedtrả lại gọn gàng các chỉ số logic của những lần không phải là lần xuất hiện đầu tiên, vì vậy !duplicated()trả về các chỉ số của những lần xuất hiện đầu tiên và x%in%wtrả về các chỉ số logic cho xnhững lần xuất hiện w. Khéo léo.


6

Java 8, 117 110 byte

a->s->{for(String x:a)for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)";s.matches(x);s=s.replaceAll(x,"$1$3"));return s;}

Giải trình:

Hãy thử trực tuyến.

a->s->{                // Method with String-array and String parameters and String return
  for(String x:a)      //  Loop over the input-array
    for(x="(?i)(.*"+x+".* )"+x+"( |$)(.*)";
                       //   Regex to match
        s.matches(x);  //   Inner loop as long as the input matches this regex
      s=s.replaceAll(x,"$1$3")); 
                       //    Replace the regex-match with the 1st and 3rd capture groups
  return s;}           //  Return the modified input-String

Giải thích thêm cho regex:

(?i)(.*"+x+".* )"+x+"( |$)(.*)   // Main regex to match:
(?i)                             //  Enable case insensitivity
    (                            //  Open capture group 1
     .*                          //   Zero or more characters
       "+x+"                     //   The input-String
            .*                   //   Zero or more characters, followed by a space
               )                 //  End of capture group 1
                "+x+"            //  The input-String again
                     (           //  Open capture group 2
                       |$        //   Either a space or the end of the String
                         )       //  End of capture group 2
                          (      //  Open capture group 3
                           .*    //   Zero or more characters
                             )   //  End of capture group 3

$1$3                             // Replace the entire match with:
$1                               //  The match of capture group 1
  $3                             //  concatted with the match of capture group 3

4

MATL , 19 18 byte

"Ybtk@kmFyfX<(~)Zc

Đầu vào là: một mảng ô của chuỗi, sau đó là chuỗi.

Hãy thử trực tuyến! Hoặc xác minh tất cả các trường hợp thử nghiệm .

Làm thế nào nó hoạt động

"        % Take 1st input (implicit): cell array of strings. For each
  Yb     %   Take 2nd input (implicit) in the first iteration: string; or
         %   use the string from previous iteration. Split on spaces. Gives
         %   a cell array of strings
  tk     %   Duplicate. Make lowercase
  @k     %   Push current string from the array taken as 1st input. Make
         %   lowercase
  m      %   Membership: gives true-false array containing true for strings
         %   in the first input argument that equal the string in the second
         %   input argument
  F      %   Push false
  y      %   Duplicate from below: pushes the true-false array again
  f      %   Find: integer indices of true entries (may be empty)
  X<     %   Minimum (may be empty)
  (      %   Assignment indexing: write false in the true-false array at that
         %   position. So this replaces the first true (if any) by false
  ~      %   Logical negate: false becomes true, true becomes false
  )      %   Reference indexing: in the array of (sub)strings that was
         %   obtained from the second input, keep only those indicated by the
         %   (negated) true-false array
  Zc     %   Join strings in the resulting array, with a space between them
         % End (implicit). Display (implicit)

3

Perl 5 , 49 byte

@B=<>;$_=join$",grep!(/^$_$/xi~~@B&&$v{+lc}++),@F

Hãy thử trực tuyến!

Đã lưu 9 (!!) byte nhờ @TonH rửa mặt !


1
Điều này dường như thất bại cho This is a test Will this be correct Both will be removed+ this will. Hai từ thứ hai được loại bỏ một cách chính xác, nhưng nó cũng loại bỏ besau từ thứ hai willvì một số lý do.
Kevin Cruijssen

1
@KevinCruijssen Hmmm, tôi có thể thấy tại sao điều đó xảy ra vào lúc này. Tôi sẽ thử và xem xét đúng vào bữa trưa ngày mai, nhưng giờ tôi đã sửa với chi phí +4. Cảm ơn vì đã cho tôi biết!
Dom Hastings

Dành cho 49:@B=<>;$_=join$",grep!(/^$_$/xi~~@B&&$v{+lc}++),@F
TonMedel 24/2/18

@TonHosp Ahh, đã dành một thời gian để cố gắng để lcđược gọi mà không có parens. Tuyệt vời! Và sử dụng regex chống lại mảng tốt hơn nhiều , Cảm ơn bạn! Tôi đấu tranh để nhớ tất cả các mẹo của bạn!
Dom Hastings

2

Bình thường, 27 byte

jdeMf!}r0eT@mr0dQmr0dPT._cz

Dùng thử trực tuyến

Giải trình

jdeMf!}r0eT@mr0dQmr0dPT._cz
                          z  Take the string input.
                       ._c   Get all the prefixes...
    f    eT@                 ... which end with something...
     !}         Q    PT      ... which is not in the input and the prefix...
       r0   mr0d mr0d        ... case insensitive.
jdeM                         Join the ends of each valid prefix.

Tôi chắc chắn có thể giảm 10 byte cho trường hợp kiểm tra không nhạy cảm, nhưng tôi không biết làm thế nào.


2

Stax , 21 byte CP437

åìøΓ²¬$M¥øHΘQä~╥ôtΔ♫╟

25 byte khi giải nén,

vjcm[]Ii<;e{vm_]IU>*Ciyj@

Kết quả là một mảng. Đầu ra thuận tiện cho Stax là một yếu tố trên mỗi dòng.

Chạy và gỡ lỗi trực tuyến!

Giải trình

vj                           Convert 1st input to lowercase and split at spaces,
  c                          Duplicate at the main stack
   m                         Map array with the rest of the program 
                                 Implicitly output
    []I                      Get the first index of the current array element in the array
       i<                    Test 1: The first index is smaller than the iteration index
                                 i.e. not the first appearance
         ;                   2nd input
          {vm                Lowercase all elements
             _]I             Index of the current element in the 2nd input (-1 if not found)
                U>           Test 2: The index is non-negative
                                 i.e. current element is a member of the 2nd input
                  *C         If test 1 and test 2, drop the current element
                                 and go on mapping the next
                    iyj@     Fetch the corresponding element in the original input and return it as the mapped result
                                 This preserves the original case

2

Perl 6 , 49 byte

->$_,+w{~.words.grep:{.lcw».lc||!(%){.lc}++}}

Kiểm tra nó

Mở rộng:

->              # pointy block lambda
  $_,           # first param 「$_」 (string)
  +w            # slurpy second param 「w」 (words)
{

  ~             # stringify the following (joins with spaces)

  .words        # split into words (implicit method call on 「$_」)

  .grep:        # take only the words we want

   {
     .lc        # lowercase the word being tested
               # is it not an element of
     w».lc      # the list of words, lowercased

     ||         # if it was one of the words we need to do a secondary check

     !          # Boolean invert the following
                # (returns true the first time the word was found)

     (
       %        # anonymous state Hash variable
     ){ .lc }++ # look up with the lowercase of the current word, and increment
   }
}

2

Perl 5 , 50 48 byte

Bao gồm +1cho-p

Đưa ra chuỗi mục tiêu theo sau bởi mỗi từ bộ lọc trên các dòng riêng biệt trên STDIN:

perl -pe '$"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop';echo
This is a test Will this be correct Both will be removed
this
will
^D
^D

Các chopchỉ là cần thiết để sửa chữa không gian dấu trong trường hợp từ cuối cùng bị loại bỏ

Chỉ cần mã:

$"="|";s%\b(@{[<>]})\s%$&x!$v{lc$1}++%iegx;chop

Hãy thử trực tuyến!


1

JavaScript (ES6), 98 byte

s=>a=>s.split` `.filter(q=x=>(q[x=x.toLowerCase()]=eval(`/\\b${x}\\b/i`).test(a)<<q[x])<2).join` `

1

K4 , 41 byte

Giải pháp:

{" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}

Ví dụ:

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat";("cat";"mat")]
"A cat called matt sat on a mat and wore a hat A called matt sat on a and wore a hat"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["Case for different case";enlist "case"]
"Case for different"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["the letters in the array are in a different case";enlist "In"]
"the letters in the array are a different case"

q)k){" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x}["5 times 5 is 25";(1#"5";1#"6")]
"5 times is 25"

Giải trình:

Tách trên khoảng trắng, chữ thường cả hai đầu vào, tìm kiếm kết quả khớp, loại bỏ tất cả trừ lần xuất hiện đầu tiên, nối chuỗi lại với nhau.

{" "/:x_/y@>y:,/1_'&:'(_y)~/:\:_x:" "\:x} / the solution
{                                       } / lambda with implicit x & y args
                                  " "\:x  / split (\:) on whitespace " "
                                x:        / save result as x
                               _          / lowercase x
                          ~/:\:           / match (~) each right (/:), each left (\:)
                      (_y)                / lowercase y
                   &:'                    / where (&:) each ('), ie indices of matches
                1_'                       / drop first of each result
              ,/                          / flatten
            y:                            / save result as y
         y@>                              / descending indices (>) apply (@) to y
      x_/                                 / drop (_) from x
 " "/:                                    / join (/:) on whitespace " "

1

JavaScript (Node.js) , 75 byte

f=(s,a)=>a.map(x=>s=s.replace(eval(`/\\b${x}\\b */ig`),s=>i++?"":s,i=0))&&s

Hãy thử trực tuyến!


1
Vì đây không phải là một hàm đệ quy, bạn không cần đưa f=vào số byte của mình. Bạn cũng có thể lưu một byte bằng cách cuộn các tham số, thay thế (s,a)=>bằng s=>a=>và sau đó gọi hàm bằng f(s)(a).
Xù xì

@Shaggy có, nhưng tôi thực sự quan tâm đến việc chơi golf định nghĩa của chức năng bởi vì thỏa thuận chính là chơi golf cơ thể. nhưng thx đó là một mẹo hay :)
DanielIndie

1

JavaScript ES6, 78 byte

f=(s,a,t={})=>s.split` `.filter(w=>a.find(e=>w==e)?(t[w]?0:t[w]=1):1).join` `

Làm thế nào nó hoạt động:

f=(s,a,t={})=> // Function declaration; t is an empty object by default
s.split` ` // Split the string into an array of words
.filter(w=> // Declare a function that, if it returns false, will delete the word
  a.find(e=>w==e) // Returns undeclared (false) if the word isn't in the list
  ?(t[w]?0 // If it is in the list and t[w] exists, return 0 (false)
    :t[w]=1) // Else make t[w] exist and return 1 (true)
  :1) // If the word isn't in the array, return true (keep the word for sure)
.join` ` // Rejoin the string

2
Chào mừng đến với PPCG! Vì bạn không sử dụng tên hàm fcho một cuộc gọi đệ quy, nên một hàm không tên cũng sẽ là một đệ trình hợp lệ, vì vậy bạn có thể lưu hai byte bằng cách bỏ đi f=.
Martin Ender

Chào mừng đến với PPCG! Đáng buồn là điều này thất bại khi các trường hợp khác nhau có liên quan.
Xù xì

Nếu không phải như vậy, bạn có thể giảm xuống còn 67 byte
Shaggy

@MartinEnder Cảm ơn vì tiền boa!
Ian

@Shaggy sử dụng mảng đầu vào làm đối tượng là một ý tưởng thú vị mà tôi chưa từng nghĩ đến. Tôi sẽ thử và khắc phục sự cố.
Ian

0

PowerShell v3 trở lên, 104 byte

Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s

Với chi phí là một byte, nó có thể chạy trong PS 2.0 bằng cách thay thế $Matches.0bằng $Matches[0].

Phiên bản dài:

Param($s, $w)
$w | Where-Object {$_ -and $s -match ($r = "\b$_(?: |$)")} |    # Process each word in the word list, but only if it matches the RegEx (which will be saved in $r).
    ForEach-Object {                                            # \b - word boundary, followed by the word $_, and either a space or the end of the string ($)
        $h, $t = $s -split $r                                   # Split the string on all occurrences of the word; the first substring will end up in $h(ead), the rest in $t(ail) (might be an array)
        $s = "$h$($Matches.0)$(-join $t)"                       # Create a string from the head, the first match (can't use the word, because of the case), and the joined tail array
    }
$s                                                              # Return the result

Cách sử dụng
Lưu dưới dạng Any.ps1 và gọi với chuỗi và các từ làm đối số. Nếu có nhiều hơn một từ cần được thông qua, các từ cần được gói trong @ ():

.\Whatever.ps1 -s "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat" -w @("cat", "mat")

Thay thế không có tệp (có thể được dán trực tiếp vào bảng điều khiển PS):
Lưu tập lệnh dưới dạng ScriptBlock (bên trong dấu ngoặc nhọn) trong một biến, sau đó gọi phương thức Invoke () của nó hoặc sử dụng nó với Invoke-Command:

$f={Param($s,$w)$w|?{$_-and$s-match($r="\b$_(?: |$)")}|%{$h,$t=$s-split$r;$s="$h$($Matches.0)$(-join$t)"};$s}
$f.Invoke("A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat"))
Invoke-Command -ScriptBlock $f -ArgumentList "A cat called matt sat on a mat and wore a hat A cat called matt sat on a mat and wore a hat", @("cat", "mat")

0

Javascript, 150 byte

s=(x, y)=>{let z=new Array(y.length).fill(0);let w=[];for(f of x)(y.includes(f))?(!z[y.indexOf(f)])&&(z[y.indexOf(f)]=1,w.push(f)):w.push(f);return w}

Bên cạnh các vấn đề với việc chơi gôn (hãy xem các giải pháp JS khác cho một số mẹo ở đó), điều này lấy đầu vào đầu tiên là một mảng các từ và xuất ra một loạt các từ không được phép của thông số thách thức. Nó cũng thất bại khi các trường hợp khác nhau có liên quan.
Xù xì

@Shaggy "Đầu ra có thể là giá trị trả về từ hàm" Điều này có vẻ như nó trả về một giá trị từ hàm?
aimorris

0

Sạch sẽ , 153 142 138 134 byte

import StdEnv,StdLib,Text
@ =toUpperCase
$s w#s=split" "s
=join" "[u\\u<-s&j<-[0..]|and[i<>j\\e<-w,i<-drop 1(elemIndices(@e)(map@s))]]

Hãy thử trực tuyến!

Xác định chức năng $ :: String [String] -> String, gần như thực hiện những gì thách thức mô tả. Nó tìm và loại bỏ mọi lần xuất hiện sau lần đầu tiên, cho mỗi từ mục tiêu.


0

Võng mạc, 46 37 byte

+i`(^|,)((.+),.*\3.* )\3( |$)
$2
.*,

-14 byte nhờ @Neil và +5 byte cho sửa lỗi.

Nhập theo định dạng word1,word2,word3,sentence , vì tôi không chắc chắn làm thế nào để có đầu vào nhiều dòng (trong đó các đầu vào được sử dụng khác nhau) ..

Giải trình:

Hãy thử trực tuyến.

+i`(^|,)((.+),.*\3.* )\3( |$)   Main regex to match:
+i`                              Enable case insensitivity
   (^|,)                          Either the start of the string, or a comma
        (                         Open capture group 2
         (                         Open capture group 3
          .+                        1 or more characters
            )                      Close capture group 3
             ,                     A comma
              .*                   0 or more characters
                \3                 The match of capture group 3
                  .*               0 or more characters, followed by a space
                     )            Close capture group 2
                      \3          The match of capture group 2 again
                        ( |$)     Followed by either a space, or it's the end of the string
$2                              And replace everything with:
                                 The match of capture group 2

.*,                             Then get everything before the last comma (the list)
                                 and remove it (including the comma itself)

1
Như đã viết, bạn có thể đơn giản hóa dòng đầu tiên +i`((.+),.*\2.* )\2( |$)và dòng thứ hai $1nhưng tôi nhận thấy rằng mã của bạn không thành công often,he intended to keep ten geese.
Neil

@Neil Cảm ơn vì đã chơi golf -14 và đã sửa lỗi bằng +1.
Kevin Cruijssen

... ngoại trừ việc này hiện không thành công ở một trong các trường hợp thử nghiệm ban đầu ...
Neil

@Neil Ah oops .. Đã sửa lại cho +4 byte.
Kevin Cruijssen

Chà, tin tốt là tôi nghĩ bạn có thể sử dụng \bthay vì (^|,), nhưng tin xấu là tôi nghĩ bạn cần \b\3\b(mặc dù chưa nghĩ ra một trường hợp thử nghiệm phù hợp nào).
Neil

0

Màu đỏ , 98 byte

func[s w][foreach v w[parse s[thru[any" "v ahead" "]any[to remove[" "v ahead[" "| end]]| skip]]]s]

Hãy thử trực tuyến!

f: func [s w][ 
    foreach v w [                   ; for each string in the array
        parse s [                   ; parse the input string as follows:
            thru [                  ; keep everything thru: 
                any " "             ; 0 or more spaces followed by
                v                   ; the current string from the array followed by
                ahead " "           ; look ahead for a space
            ]
            any [ to remove [       ; 0 or more: keep to here; then remove: 
                " "                 ; a space followed by 
                v                   ; the current string from the array
                ahead [" " | end]]  ; look ahead for a space or the end of the string
            | skip                  ; or advance the input by one 
            ]
        ]
    ]
    s                               ; return the processed string 
]

0

Husk , 13 byte

wüöVËm_Ṗ3+⁰ew

Lấy một danh sách các chuỗi và một chuỗi làm đối số, theo thứ tự này. Giả sử rằng danh sách này là trùng lặp miễn phí. Hãy thử trực tuyến!

Giải trình

wüöVËm_Ṗ3+⁰ew  Inputs: list of strings L (explicit, accessed with ⁰), string S (implicit).
               For example, L = ["CASE","for"], s = "Case for a different case".
            w  Split S on spaces: ["Case","for","a","different","case"]
 ü             Remove duplicates wrt an equality predicate.
               This means that a function is called on each pair of strings,
               and if it returns a truthy value, the second one is removed.
  öVËm_Ṗ3+⁰e    The predicate. Arguments are two strings, say A = "Case", B = "case".
           e    Put A and B into a list: ["Case","case"]
         +⁰     Concatenate with L: ["CASE","for","Case","case"]
       Ṗ3       All 3-element subsets: [["CASE","for","Case"],["CASE","for","case"],
                                        ["CASE","Case","case"],["for","Case","case"]]
  öV            Does any of them satisfy this:
    Ë            All strings are equal
     m_          after converting each character to lowercase.
                In this case, ["CASE","Case","case"] satisfies the condition.
               Result: ["Case","for","a","different"]
w              Join with spaces, print implicitly.

0

Tối thiểu , 125 byte

=a () =b a 1 get =c a 0 get " " split
(:d (b d in?) ((c d in?) (d b append #b) unless) (d b append #b) if) foreach
b " " join

Đầu vào nằm quottrên ngăn xếp với Chuỗi đầu vào là phần tử đầu tiên và một quottrong các chuỗi trùng lặp là phần tử thứ hai, nghĩa là

("this sentence has no matches" ("ten" "cheese"))


0

AWK , 120 byte

NR%2{for(;r++<NF;)R[tolower($r)]=1}NR%2==0{for(;i++<NF;$i=$(i+s))while(R[x=tolower($(i+s))])U[x]++?++s:i++;NF-=s}NR%2==0

Hãy thử trực tuyến!

Phần "xóa khoảng trắng" khiến điều này trở nên khó khăn hơn tôi nghĩ. Đặt trường thành"" , loại bỏ một trường, nhưng để lại một dấu phân cách bổ sung.

Liên kết TIO có thêm 28 byte để cho phép nhiều mục nhập.

Đầu vào được đưa ra trên 2 dòng. Dòng đầu tiên là danh sách các từ và dòng thứ hai là "câu". Lưu ý rằng "từ" và "từ" không được coi là giống hệt với dấu chấm câu đính kèm. Có yêu cầu về dấu câu có thể sẽ khiến vấn đề này trở nên thú vị hơn .


0

Ruby , 63 61 60 59 byte

->s,w{w.any?{|i|s.sub! /\b(#{i}\b.*) #{i}\b/i,'\1'}?redo:s}

Hãy thử trực tuyến!

Một phiên bản ngắn hơn phân biệt chữ hoa chữ thường và không thành công ~ cứ sau 10 15 lần vì tính ngẫu nhiên (37 byte)

->s,w{s.uniq{|i|w.member?(i)?i:rand}}

0

Python 2 , 140 byte

from re import*
p='\s?%s'
S,A=input()
for a in A:S=sub(p%a,lambda s:s.end()==search(p%a,S,flags=I).end()and s.group()or'',S,flags=I)
print S

Hãy thử trực tuyến!

Giải trình:

re.sub(..)có thể lấy làm đối số một hàm thay vì chuỗi thay thế. Vì vậy, ở đây chúng tôi có một số lambda ưa thích. Hàm được gọi cho mỗi lần xuất hiện của mẫu và một đối tượng được truyền cho hàm này - matchobject. Đối tượng này có thông tin về sự xuất hiện thành lập. Tôi quan tâm đến chỉ số của sự xuất hiện này, có thể được truy xuất bằng start()hoặcend() chức năng. Latter ngắn hơn nên được sử dụng.

Để loại trừ việc thay thế từ xuất hiện đầu tiên của từ, tôi đã sử dụng một hàm tìm kiếm regex khác để lấy chính xác một từ và sau đó so sánh các chỉ mục, sử dụng tương tự end()

Cờ re.Ilà phiên bản ngắn củare.IGNORECASES

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.